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

百般思念 提交于 2019-12-25 05:33:30

问题


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

回答1:


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

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




回答2:


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:


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

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

Its messy, but you dont need to solve locale.



来源:https://stackoverflow.com/questions/30623479/how-to-parse-1-234-56-in-java-as-double

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!