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:

  • http://www.hashref.com Xavier Noria

    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.

  • http://www.rubyfleebie.com Frank

    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″

  • http://www.kerristevens.com Kerri Stevens

    Thanks for the tip. I am using rails to build a financial application and found the exact answer I was looking for right here!

  • http://www.scribd.com/doc/175665147/Rpp-Kurikulum-2013-Lengkap-SD-SMP-SMA-SMK-Terbaru kurikulum 2013

    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.

  • peter marien

    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