【问题标题】:How can I parse a String to BigDecimal? [duplicate]如何将字符串解析为 BigDecimal? [复制]
【发布时间】:2013-08-16 09:49:58
【问题描述】:

我有这个字符串:10,692,467,440,017.120(这是一个数量)。

我想将其解析为 BigDecimal。问题是我尝试了 DecimalFormat 和 NumbeFormat 都是徒劳的。

【问题讨论】:

  • 向我们展示您的尝试。我们会提供帮助

标签: java string parsing bigdecimal decimalformat


【解决方案1】:

试试这个

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

还请记住,decimalFormat.parse 可以抛出 ParseException,因此您需要处理它(使用 try/catch)或抛出它并让程序的另一部分处理它

【讨论】:

  • 如果切换分组和小数分隔符,上面的代码将不起作用。如果 DecimalFormat 按照DecimalFormat res = new DecimalFormat(); res.setDecimalFormatSymbols(symbols); res.applyLocalizedPattern(formatter); 进行初始化,它将起作用
【解决方案2】:

试试这个

 String str="10,692,467,440,017.120".replaceAll(",","");
 BigDecimal bd=new BigDecimal(str);

【讨论】:

  • @jlordo 是的,我编辑了我的答案
【解决方案3】:

尝试正确的构造函数 http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String)

你可以直接用 String 实例化 BigDecimal ;)

例子:

BigDecimal bigDecimalValue= new BigDecimal("0.5");

【讨论】:

  • BigDecimal 无法解析示例字符串。
  • 字符串值会失败:1,000 逗号在构造转换中不小心。
【解决方案4】:

BigDecimal 提供了一个字符串构造函数。您需要通过正则表达式或String filteredString=inString.replaceAll(",","") 删除号码中的所有逗号。

然后您只需拨打BigDecimal myBigD=new BigDecimal(filteredString);

您也可以创建NumberFormat 并调用setParseBigDecimal(true)。然后parse( 会给你一个 BigDecimal 而不用担心手动格式化。

【讨论】:

    猜你喜欢
    • 2012-12-30
    • 2020-07-08
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    相关资源
    最近更新 更多