I had a float attribute in a Rails application and wanted to strip non-significant zeros when displaying it on a page. With the number_with_precision helper from ActionView, that’s a trivial thing:
number_with_precision( 3.50, strip_insignificant_zeros: true, precision: 2 ) # => '3.5'
5 thoughts on “How To Strip Insignificant Zeros From a Float In Rails”
Just in case, note that the Ruby sees no zero in the literal 3.50, it’s the same as 3.5.
The zero this option is stripping is the one in the string % would otherwise generate because the precision is 2.
Thanks for the clarification, Xavier.
In my case I needed to keep the precision at 2 since I wanted “2.75” and not “2.8”. The only thing I didn’t want were strings like “2.50” or “2.00”
Thanks for the tip. I am using rails to build a financial application and found the exact answer I was looking for right here!
Most driver education books provide very clear and precise text and are well written. A book that provides a program that helps students manage the risks and responsibilities of driving might be a good alternative to a regular course.
Don’t know actionview but why be dependent of something when you can it with base Ruby with one line ?
result = result.to_i if result == result.to_i