losing precision converting from java BigDecimal to double

后端 未结 5 1475
遥遥无期
遥遥无期 2020-12-15 08:56

I am working with an application that is based entirely on doubles, and am having trouble in one utility method that parses a string into a double. I\'ve found a fix where

5条回答
  •  庸人自扰
    2020-12-15 09:56

    The problem is that a double can hold 15 digits, while a BigDecimal can hold an arbitrary number. When you call toDouble(), it attempts to apply a rounding mode to remove the excess digits. However, since you have a lot of 9's in the output, that means that they keep getting rounded up to 0, with a carry to the next-highest digit.

    To keep as much precision as you can, you need to change the BigDecimal's rounding mode so that it truncates:

    BigDecimal bd1 = new BigDecimal("12345.1234599999998");
    System.out.println(bd1.doubleValue());
    
    BigDecimal bd2 = new BigDecimal("12345.1234599999998", new MathContext(15, RoundingMode.FLOOR));
    System.out.println(bd2.doubleValue());
    

提交回复
热议问题