Reputation: 6383
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.
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')
Upvotes: 45
Views: 19675
Reputation: 3090
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.
Upvotes: 29
Reputation: 183779
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)
Upvotes: 2
Reputation: 605
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. :-)
Upvotes: -2
Reputation: 1013
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
Upvotes: 6
Reputation: 63
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
Upvotes: 3
Reputation: 4691
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
Upvotes: 3