Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse numbers from different locale formats?

Is there an already existing solution that can parse all the numbers below?

"300.00"
"2.300,00"
"2,300.00"
like image 348
Geo Avatar asked Jan 29 '13 00:01

Geo


People also ask

What does toLocaleString() do?

The toLocaleString() method returns a string with a language-sensitive representation of this date. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .

How to get the number format in java?

myNumber = nf. parse(myString); Use getInstance or getNumberInstance to get the normal number format. Use getIntegerInstance to get an integer number format.

What is number format class?

NumberFormat is a Java class for formatting and parsing numbers. With NumberFormat , we can format and parse numbers for any locale. NumberFormat allows us to round values, set decimal separators, set the number of fraction digits, or format values according to a specific locale.


1 Answers

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")
like image 90
Arman H Avatar answered Sep 27 '22 22:09

Arman H