java 如何将字符串数字解析为 BigDecimal

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14346403/
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-10-31 15:56:57  来源:igfitidea点击:

How to parse a string number into a BigDecimal

javaregexparsing

提问by Yoda

Possible Duplicate:
Safe String to BigDecimal conversion

可能的重复:
安全字符串到 BigDecimal 的转换

Is there any ultimate parse function in java which can analyze type of the number given in string and return its value in object of class Number or similar. I would like to convert string into bigDecimal or Number and put t into collection, sometimes I have string like 2.23or 2,23or 2or BigInteger like 233242424242424242.

java中是否有任何最终的解析函数可以分析字符串中给出的数字的类型并在类Number或类似的对象中返回其值。我想转换成字符串或BigDecimal的数量,并把牛逼到收藏,有时我有串状2.232,232或类似的BigInteger 233242424242424242

回答by Nivas

If all you want is to parse a Stringto a BigDecimal, you can use the constructorthat gets a string as a argument. The constructor takes care of the basic parsing.

如果您只想String将 a解析为 a BigDecimal,则可以使用获取字符串作为参数的构造函数。构造函数负责基本的解析。

BigDecimal b = new BigDecimal(str);

For complex parsing (involving thousands separators), you can use the methods in the DecimalFormatclass with setParseBigDecimalset to true.

对于复杂的解析(涉及千位分隔符),您可以使用设置为的DecimalFormat类中的方法。setParseBigDecimaltrue

回答by Petr

The documentation of the Double method has an excellent example of the regexp you are looking for: http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#valueOf(java.lang.String)

Double 方法的文档有一个很好的正则表达式示例:http: //docs.oracle.com/javase/6/docs/api/java/lang/Double.html#valueOf(java.lang.字符串)