How To Strip Insignificant Zeros From a Float In Rails
by Frank
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"







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″