Conditional formatting of integers using decimal places


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.


Using floating point numbers

Convert the integer number to float64, divide it 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):


Using integers

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:

The last 2 digits are the remainder of dividing by 100, the rest is the result of integer division by 100. You can format these 2 numbers depending on the remainder like this:

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

Try this one on the Go Playground.

Answered By – icza

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.