Adam MilliganAdam Milligan
Standup 10/24/2008: Floating point number formatting and you
edit Posted by Adam Milligan on Friday October 24, 2008 at 05:58PM

Interesting Things

We have a project that generates a lot of highly precise floating point numbers. However, we primarily want to display these numbers with only two decimal places of precision. In addition, we want to display these numbers with standard comma delimiters to the left of the decimal point.

Sadly, the Ruby #sprintf method provides the former functionality, but not the latter. What to do? Use a Rails helper, of course.

The NumberHelper from ActionView provides some useful functionality, so we used that. As it turns out, we found the best way to get the formatting we want to be using the #number_to_currency function with no denomination.

Also, rather than mixing the entire helper into the Float class for just one method, we chose to mix the helper into a nested class and expose only the functionality that interests us. The result looks something like this:

class Float
  class RailsNumberHelpers
    extend ActionView::Helpers::NumberHelper
  end

  def formatted
    s = Float::RailsNumberHelpers.number_to_currency(self, :unit => '', :precision => 2).chomp('0')
  end
end

Comments

  1. grosser grosser on November 01, 2008 at 05:08PM

    Something similar using humanize(like string):

    http://pragmatig.wordpress.com/2008/10/25/numbers-for-humans-humanize-for-numeric/