How to parse “1,234.56” in Java as Double?

2019-09-07 17:37发布

I am having trouble parsing "1,234.56" in Java, a similar question recommend using French locale in number formatting, but it is parsing the result incorrectly. Here is what I have:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234.56");
System.out.println(number.doubleValue()); // Should get 1234.56, got 1.234 instead
Number number = format.parse("1,234,567.89");
System.out.println(number.doubleValue());  // Should get 1234567.89

3条回答
对你真心纯属浪费
2楼-- · 2019-09-07 18:06

French locale has the decimal point represented by a comma. You'll need to use the US locale:

NumberFormat format = NumberFormat.getInstance(Locale.US);

or Locale.ENGLISH based on the language:

NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
查看更多
看我几分像从前
3楼-- · 2019-09-07 18:12

You could use string replacement and replace "," for ""

format.parse(("1,234.56").replace(",", ""));

Its messy, but you dont need to solve locale.

查看更多
我命由我不由天
4楼-- · 2019-09-07 18:15

1,234.56 is not French notation. (Something like 1.234,56 is).

Change your locale to Locale.ENGLISH, Locale.US, or similar

查看更多
登录 后发表回答