Pivotal Labs

Main menu

Skip to primary content
Skip to secondary content
  • About
  • Case Studies
  • Team
    • Executives
    • Locations
      • San Francisco (HQ)
      • Boston
      • Boulder
      • Denver
      • London
      • Los Angeles
      • New York
  • Community
    • Blogs
    • Tech Talks
    • Events
  • Careers
    • Lifestyle
    • Principles & Practices
    • Benefits
    • FAQ
    • Apply
  • Contact
    • Press Room
    • Press Releases
    • In The News
    • Press Kit
  • All
  • Labs
  • Standup
  • Tracker

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

Adam Milligan
Friday, October 24, 2008

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
  • 0 Shares
  • Share on Facebook
  • Share on Twitter

One comment

  1. grosser says:

    Something similar using humanize(like string):

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

    November 1, 2008 at 5:08 pm

Add New Comment Cancel reply

Your email address will not be published.

Adam Milligan

Adam Milligan
New York

Recent Posts

  • Why not to use ARC
  • Cedar Expectations
  • The Trouble With Expectations in Objective C
Subscribe to Adam's Feed

Author Topics

blocks (2)
cplusplus (4)
ios (10)
objective-c (13)
cedar (11)
testing (16)
opensource (5)
xcode4 (1)
rake (4)
access control (3)
ci (2)
jasmine (1)
javascript (3)
ie6 (1)
addiction (1)
activerecord (7)
nested_attributes (1)
rails (12)
actionpack (1)
refactoring (1)
agile (4)
ruby (8)
actionview (1)
threads (1)
functors (2)
brownbags (2)
solr (1)
  • About
  • Case Studies
  • Team
  • Community
  • Careers
  • Contact
  • Labs
  • Events

Contact Us

contact@pivotallabs.com
+1 415-77-PIVOT
TwitterLinkedInFacebook

Pivotal Tracker

Tracker is the award-winning agile project management tool that enables real-time collaboration around a shared, prioritized backlog.
Visit pivotaltracker.com >