带有大括号的Java负bigdecimal值

时间:2013-02-13 17:41:06

标签: java

我有一个字符串,我正在尝试解析为BigDecimal。我正在使用以下正则表达式去除所有非货币符号,但 - ,。()$除外。一旦它被剥离,我就会尝试用剩余的值创建一个BigDecimal。当括号中出现负值时,问题就开始了。有没有人对如何修复这个实例有任何建议?

(1000.00) fails

我假设我必须以某种方式将括号转换为负号。

代码示例。

public BigDecimal parseClient(Field field, String clientValue, String message) throws ValidationException {
    if (clientValue == null) {
        return null;
    }

    try {
        clientValue = clientValue.replaceAll( "[^\\d\\-\\.\\(\\)]", "" );
        return new BigDecimal(clientValue.toString());
    } catch (NumberFormatException ex) {
        throw new ValidationException(message);
    }
}

3 个答案:

答案 0 :(得分:2)

您需要自己检测()个字符,然后将它们删除,从字符串的其余部分创建一个BigDecimal,然后取消它。

if (clientValue.startsWith('(') && clientValue.endsWith(')'))
{
   return new BigDecimal(clientValue.substring(1, clientValue.length() - 1)).negate();
}
else
{
   return new BigDecimal(clientValue);
}

答案 1 :(得分:1)

是什么让你认为括号被BigDecimal正确解释? (1000.00)输入错误according to the documentation。您必须使用-符号(-1000.00)。支持的格式在JavaDoc中严格定义。一般来说,它是可选符号(+-),后跟数字,点(.)和指数。

例如,这是有效输入:-1.1e-10

答案 2 :(得分:0)

我认为DecimalFormat是适合这项工作的更合适的工具:

DecimalFormat myFormatter = new DecimalFormat("¤#,##0.00;(¤#,##0.00)");
myFormatter.setParseBigDecimal(true);
BigDecimal result = (BigDecimal) myFormatter.parse("(1000.00)");
System.out.println(result); // -1000.00 for Locale.US
System.out.println(myFormatter.parse("($123,456,789.12)")); // -123456789.12

正如您所看到的,它不仅会处理负面模式,还会处理货币符号,小数和分组分隔符,本地化问题等。

请查看The Java Tutorials: Customizing Formats了解更多信息。