How To Strip Insignificant Zeros From a Float In Rails

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

  1. 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.

  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”

  3. 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.

  4. 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

Leave a Reply

Your email address will not be published. Required fields are marked *