Reputation: 96827
Is there an already existing solution that can parse all the numbers below?
"300.00"
"2.300,00"
"2,300.00"
Upvotes: 5
Views: 1374
Reputation: 5618
Try using the money
gem:
$ gem install money
Then you can do:
require 'money'
test1 = Money.parse("300.00")
test2 = Money.parse("2.300,00")
test3 = Money.parse("2,300.00")
test1.currency # #<Money::Currency id: usd, priority: 1, symbol_first: true, thousands_separator: ,, html_entity: $, decimal_mark: ., name: United States Dollar, symbol: $, subunit_to_unit: 100, iso_code: USD, iso_numeric: 840, subunit: Cent>
test1.amount # 300.0
test1.dollars # 300.0
test1.cents # 30000
test1.currency_as_string # USD
test1.separator # .
test1.thousands_separator # ,
test1.delimiter # ,
EDIT: the old money
gem has split into two parts: money
and monetize
. The new money
class only handles creating, manipulating and converting currencies between money
objects.
To parse objects (including strings) into money
objects, you should use the monetize
gem instead:
$ gem install monetize
Monetize.parse("USD 100")
Monetize.parse("£100")
Monetize.parse_collection("€80, $100")
Upvotes: 6