我如何解析String到BigDecimal? [英] How can i parse a String to BigDecimal?

查看:921
本文介绍了我如何解析String到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. Any help?

推荐答案

试试这个

// 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

这篇关于我如何解析String到BigDecimal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆