Home > Net >  Conditional formatting of integers using decimal places
Conditional formatting of integers using decimal places

Time:03-16

I have the following situation: I'll be receiving integers and have to format them according to the following rules:

10000 -> 100 // removing the last "00"
10010 -> 100.1 // removing the last "0", and adding a decimal place
10011 -> 100.11 // adding two decimal places 

How this can be done? Thanks so much in advance.

CodePudding user response:

Divide the number by 100 and use the %g verb of the fmt package, it removes trailing zeros:

For floating-point values, width sets the minimum width of the field and precision sets the number of places after the decimal, if appropriate, except that for %g/%G precision sets the maximum number of significant digits (trailing zeros are removed).

To avoid "large" numbers reverting to %e scientific notation (numbers with more than the default precision which is 6 for %g), specify the width explicitly, something like this:

fmt.Printf("%.12g\n", float64(v)/100)

Testing it:

for _, v := range []int{
    10000, 10010, 10011,
    10000000, 10000010, 10000011,
    10000000000, 10000000010, 10000000011,
} {
    fmt.Printf("%.12g\n", float64(v)/100)
}

This will output (try it on the Go Playground):

100
100.1
100.11
100000
100000.1
100000.11
100000000
100000000.1
100000000.11

Without converting to floating point numbers (and relying on the trailing zero removal of %g), this is how you could do it using integer arithmetic:

switch q, r := v/100, v0; {
case r == 0:
    fmt.Println(q)
case r == 0:
    fmt.Printf("%d.%d\n", q, r/10)
default:
    fmt.Printf("%d.d\n", q, r)
}

Try this one on the Go Playground.

  • Related