Only show decimal point if floating point component is not .00 sprintf/printf
-
10-07-2019 - |
Question
I am pretty formatting a floating point number but want it to appear as an integer if there is no relevant floating point number.
I.e.
- 1.20 -> 1.2x
- 1.78 -> 1.78x
- 0.80 -> 0.8x
- 2.00 -> 2x
I can achieve this with a bit of regex but wondering if there is a sprintf
-only way of doing this?
I am doing it rather lazily in ruby like so:
("%0.2fx" % (factor / 100.0)).gsub(/\.?0+x$/,'x')
Solution
You want to use %g
instead of %f
:
"%gx" % (factor / 100.00)
OTHER TIPS
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)
# => 13
number_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.
I ended up with
price = price.round(precision)
price = price % 1 == 0 ? price.to_i : price.to_f
this way you even get numbers instead of strings
I just came across this, the fix above didnt work, but I came up with this, which works for me:
def format_data(data_element)
# if the number is an in, dont show trailing zeros
if data_element.to_i == data_element
return "%i" % data_element
else
# otherwise show 2 decimals
return "%.2f" % data_element
end
end
Here's another way:
decimal_precision = 2
"%.#{x.truncate.to_s.size + decimal_precision}g" % x
Or as a nice one-liner:
"%.#{x.truncate.to_s.size + 2}g" % x
Easy with Rails: http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision
number_with_precision(value, precision: 2, significant: false, strip_insignificant_zeros: true)
I was looking for a function to truncate (not approximate) a float or decimal number in Ruby on Rails, I figure out the follow solution to do that:
you guys can try in your console, the example:
>> a=8.88
>> (Integer(a*10))*0.10
>> 8.8
I hope it helps somebody. :-)