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:

[ruby light="true"]
strip_insignificant_zeros: true,
precision: 2
# => "3.5"

6 thoughts on “How To Strip Insignificant Zeros From a Float In Rails

  1. Xavier Noria says:

    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. Frank says:

    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. Thanks for the tip. I am using rails to build a financial application and found the exact answer I was looking for right here!

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

  5. Kina says:

    Te recomendamos tambien qque te descarges el hack de Clash oof Clans.

  6. trends which can be creating this workplace revolution.

Leave a Reply

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


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>