Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

Standup 10/24/2008: Floating point number formatting and you

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

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

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *