如何在不出错的情况下将 String 解析为 BigDecimal

How to parse String to BigDecimal without getting error

当我想将值从字符串数组解析为 BigDecimal 时出现此错误:

Exception in thread "main" java.text.ParseException: Unparseable number: "86400864008640086400222"

我正在互联网上搜索解决此问题的方法。也许你们知道?

使用 BigDecimal 不是我的主意,但不幸的是我不得不这样做。我创建了一些应该将值从 String 更改为 BigDecimal 和 return 的代码:

public static BigDecimal parseCurrencyPrecise (String value) throws ParseException
{
    NumberFormat  format = NumberFormat.getCurrencyInstance ();
    if (format instanceof DecimalFormat)
        ((DecimalFormat) format).setParseBigDecimal (true);

    Number  result = format.parse (value);
    if (result instanceof BigDecimal)
        return (BigDecimal) result;
    else {
        // Oh well...
        return new BigDecimal (result.doubleValue ());
    }
}

这是我尝试解析时的代码:

public void Function() throws ParseException {
    String [] array;
    array=OpenFile().split("\s");
    for(int i = 10 ;i < array.length; i+= 11) {
        BigDecimal EAE = parseCurrencyPrecise(array[i]);
        System.out.println(EAE);
    }
}

OpenFile函数打开有数据的文件,这样读取这个L temp+=line+" "; 这就是我用 \s 分割的原因。这对我来说适用于字符串和整数,但我在使用 BigDecimal 时遇到了问题。

你好,

您可以使用 BigDecimal(String val) 构造函数,而不是自己处理解析。来自 Javadoc

BigDecimal(String val)
Translates the string representation of a BigDecimal into a BigDecimal

例如:

BigDecimal bigDecimal = new BigDecimal("86400864008640086400222");

有关构造函数采用的格式,请参阅 Javadoc。

有什么理由不能使用构造函数吗?看起来你让它变得比它必须的更复杂。这对我有用:

System.out.println(new BigDecimal("86400864008640086400222"));