Java 如何将字符串解析为 BigDecimal?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18231802/
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
How can i parse a String to BigDecimal?
提问by BenMansourNizar
I have this String: 10,692,467,440,017.120 (it's an amount).
我有这个字符串:10,692,467,440,017.120(这是一个数量)。
I want to parse it to a BigDecimal. The problem is that I have tried both DecimalFormat and NumbeFormat in vain. Any help?
我想将其解析为 BigDecimal。问题是我徒劳地尝试了 DecimalFormat 和 NumbeFormat。有什么帮助吗?
采纳答案by René Link
Try this
尝试这个
// Create a DecimalFormat that fits your requirements
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);
// parse the string
BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse("10,692,467,440,017.120");
System.out.println(bigDecimal);
If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)
如果您正在构建具有 I18N 支持的应用程序,您应该使用 DecimalFormatSymbols(Locale)
Also keep in mind that decimalFormat.parse
can throw a ParseException
so you need to handle it (with try/catch) or throw it and let another part of your program handle it
还要记住,decimalFormat.parse
可以抛出 aParseException
所以你需要处理它(使用 try/catch)或抛出它并让你的程序的另一部分处理它
回答by nanofarad
BigDecimal offers a string constructor. You'll need to strip all commas from the number, via via an regex or String filteredString=inString.replaceAll(",","")
.
BigDecimal 提供了一个字符串构造函数。您需要通过正则表达式或String filteredString=inString.replaceAll(",","")
.
You then simply call BigDecimal myBigD=new BigDecimal(filteredString);
然后你只需调用 BigDecimal myBigD=new BigDecimal(filteredString);
You can also create a NumberFormat
and call setParseBigDecimal(true)
. Then parse(
will give you a BigDecimal without worrying about manually formatting.
您还可以创建一个NumberFormat
并调用setParseBigDecimal(true)
. 然后parse(
会给你一个 BigDecimal 而不必担心手动格式化。
回答by Rene M.
Try the correct constructor http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String)
尝试正确的构造函数 http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String)
You can directly instanciate the BigDecimal with the String ;)
您可以使用字符串直接实例化 BigDecimal ;)
Example:
例子:
BigDecimal bigDecimalValue= new BigDecimal("0.5");
回答by Ruchira Gayan Ranaweera
Try this
尝试这个
String str="10,692,467,440,017.120".replaceAll(",","");
BigDecimal bd=new BigDecimal(str);