Java BigDecimal 可以用逗号代替点吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18714360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:25:07  来源:igfitidea点击:

Java BigDecimal can have comma instead dot?

javadecimalbigdecimal

提问by Jean Tehhe

I have a string value that I want to assign to a BigDecimal. When I update the decimal value with a number like 100.23, it works fine but when I update it with a number like 100,23the code throws an exception. Why is that?

我有一个要分配给 BigDecimal 的字符串值。当我用类似的数字更新十进制值时100.23,它工作正常,但是当我用类似100,23代码的数字更新它时会引发异常。这是为什么?

采纳答案by No Idea For Name

because you tried to put a "," in a number.

因为您试图在数字中放入“,”。

you can use this code to parse a number with comma:

您可以使用此代码来解析带逗号的数字:

NumberFormat.getNumberInstance(Locale.FRANCE).parse("265,858")

you should also use float or double if there is no particular reason you use decimal.

如果没有特殊原因您使用十进制,您也应该使用 float 或 double。

回答by Kevin Bowersox

The BigDecimal(String)constructor documentationlists all valid formats and characters. Notice that the ,is not included within this list.

BigDecimal(String)构造函数的文档列出了所有有效格式和字符。请注意,,此列表中未包含 。

回答by Kayz

If you can't be sure if your String has commas or points, you can use replace(char, char)from the String class. For example myString.replace(',', '.').

如果您不能确定您的 String 是否有逗号或点,您可以使用replace(char, char)String 类。例如myString.replace(',', '.')