Only show decimal point if floating point component is not .00 sprintf/printf Only show decimal point if floating point component is not .00 sprintf/printf ruby ruby

Only show decimal point if floating point component is not .00 sprintf/printf


You want to use %g instead of %f:

"%gx" % (factor / 100.00)


You can mix and match %g and %f like so:

"%g" % ("%.2f" % number)


If you're using rails, you can use rails' NumberHelper methods:http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html

number_with_precision(13.001, precision: 2, strip_insignificant_zeros: true)# => 13number_with_precision(13.005, precision: 2, strip_insignificant_zeros: true)# => 13.01

Be careful, because precision means all digits after decimal point in this case.