Search code examples
goformatformat-string

Variable floating-point precision format string


I'm trying to print floating point numbers as percentages, and I'd like for the number of digits after the decimal place to vary as needed. Currently I have:

fmt.Printf("%.2f%%\n", 100*(value/total))

The problem is that if my percentage is, say, exactly 50, I will get the following output:

50.00%

While what I want is to get:

50%

Is there any way for the format string to indicate that a maximum of 2 digits of precision should be used, but only if needed?


Solution

  • There's no direct solution with the fmt package.

    But you can remove the dot and zeros at end with a regular expression:

    r, _ := regexp.Compile(`\.?0*$`)
    fmt.Printf("%s%%\n", r.ReplaceAllString(fmt.Sprintf("%.2f", 100*(value/total)),""))
    

    Bonus: the same regex works for any number of trailing zeros.

    Side note: You'll display 50.0041 the same way than 50, which might be a little misleading.