BigDecimal adding wrong value

后端 未结 5 1982
谎友^
谎友^ 2020-11-27 08:15

I have a BigDecimal defined like this:

private static final BigDecimal sd = new BigDecimal(0.7d);

if i print it, i get the val

5条回答
  •  被撕碎了的回忆
    2020-11-27 09:08

    Constructing a BigDecimal from a double is surprisingly complicated. First, it can only be done via the detour of a string. (You can't get the constructor with double and a MathContext right. I've tried a lot. At the latest in cases in which the number of places before the decimal point would need to change due to rounding, it becomes difficult. Hence the warning in the Javadoc that you shouldn’t use it.)

    However, even there, it is not enough with a simple String.format(), since String.format() is sensitive to the default Locale and outputs different decimal separators depending on system/VM settings, while the BigDecimal constructor always requires a dot as a decimal separator. So you have to construct your own Formatter with Locale.US. If you have this up and running, you will get a warning of an unclosed resource.

    I found this to work:

    static BigDecimal toBigDecimal(double value, int decimalPlaces) {
        String format = "%." + decimalPlaces + "f";
        try (Formatter formatter = new Formatter(Locale.US)) {
            String formatted = formatter.format(format, value).toString();
            return new BigDecimal(formatted);
        }
    }
    

提交回复
热议问题