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

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -