Search code examples
ruby-on-railsrubyroundingnumber-formatting

How to format all numbers into millions in Ruby using NumberHelper


Ruby newbie here - I'm trying to any number (including thousands) into millions, and then rounded up to 2 decimal places, eg:

1499962946.140625 => 1499.97
31135762.5 => 31.14
8952392.3125 => 8.95
77896 => 0.08
5342 => 0.01

I've tried to do this using the following but so far it is only rounding the millions correctly, and the thousands stay as thousands. I would also like to drop 'Million' and 'Thousand' from the resultant string:

number_to_human(1234567.12345, precision: 2, significant: false)
=> "1.2 Million"
number_to_human(1234.12345, precision: 2, significant: false)
=> "1.23 Thousand"

Additionally, is there a way to keep the zeros, e.g. 1276.40 instead of 1276.4 ?

Thank you!


Solution

  • What about just doing:

    > (31135762.5 / 1000000).round(2)
    # => 31.14
    

    If you want to keep the zeros, you can do that:

    > sprintf('%0.02f', 1276.4)
    # => "1276.40"
    

    But now you have a string.

    If you want you also can put this is a function:

    def format_number(num)
      sprintf('%0.02f', num / 1000000)
    end
    
    format_number(31135762.5)
    # => "31.14"