Henley Wing Chiu
Henley Wing Chiu

Reputation: 22515

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

Upvotes: 0

Views: 1206

Answers (2)

Subhash Chandra
Subhash Chandra

Reputation: 3265

Try something like this if you have an array of human readable numbers than

array.map do |elem|
    elem = elem.gsub('$','')
    if elem.include? 'B'
        elem.to_f * 1000000000
    elsif elem.include? 'M'
        elem.to_f * 1000000
    elsif elem.include? 'K'
        elem.to_f * 1000
    else
        elem.to_f
    end
end

Have a look here as well, you will find many Numbers Helpers

NumberHelper Rails.

Ruby Array human readable to actual

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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  }

Upvotes: 6

Related Questions