本文介绍了如何将字符串解析为 BigDecimal?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个字符串:10,692,467,440,017.120(这是一个数量).
I have this String: 10,692,467,440,017.120 (it's an amount).
我想将其解析为 BigDecimal.问题是我尝试了 DecimalFormat 和 NumbeFormat 都是徒劳的.
I want to parse it to a BigDecimal. The problem is that I have tried both DecimalFormat and NumbeFormat in vain.
推荐答案
试试这个
// 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);
如果您正在构建支持 I18N 的应用程序,您应该使用 DecimalFormatSymbols(Locale)
If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)
还要记住 decimalFormat.parse
可以抛出一个 ParseException
所以你需要处理它(使用 try/catch)或抛出它并让你的另一部分程序处理它
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
这篇关于如何将字符串解析为 BigDecimal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!