go - Variable floating-point precision format string -
i'm trying print floating point numbers percentages, , i'd number of digits after decimal place vary needed. have:
fmt.printf("%.2f%%\n", 100*(value/total))
the problem if percentage is, say, 50, following output:
50.00%
while want get:
50%
is there way format string indicate maximum of 2 digits of precision should used, if needed?
there's no direct solution fmt
package.
but can remove dot , zeros @ end regular expression:
r, _ := regexp.compile(`\.?0*$`) fmt.printf("%s%%\n", r.replaceallstring(fmt.sprintf("%.2f", 100*(value/total)),""))
bonus: same regex works number of trailing zeros.
side note: you'll display 50.0041
same way 50
, might little misleading.
Comments
Post a Comment