Henley Chiu Henley Chiu - 5 months ago 24
Ruby Question

How to convert human readable number to actual number in Ruby?

Is there a simple Rails/Ruby helper function to help you convert human readable numbers to actual numbers?

Such as:

1K => 1000

2M => 2,000,000

2.2K => 2200

1,500 => 1500

50 => 50

5.5M => 5500000

Answer
test = {
  '1K' => 1000,
  '2M' => 2000000,
  '2.2K' => 2200,
  '1,500' => 1500,
  '50' => 50, 
  '5.5M' => 5500000
}

class String
  def human_readable_to_i
    multiplier = {'K' => 1_000, 'M' => 1_000_000}[self.upcase[/[KM](?=\z)/]] || 1
    value = self.gsub(/[^\d.]/, '')
    case value.count('.')
    when 0 then value.to_i
    when 1 then value.to_f
    else 0
    end * multiplier
  end 
end

test.each { |k, v| raise "Test failed" unless k.human_readable_to_i == v  }