Retain precision with double in Java

前端 未结 22 3141
情歌与酒
情歌与酒 2020-11-21 05:15
public class doublePrecision {
    public static void main(String[] args) {

        double total = 0;
        total += 5.6;
        total += 5.8;
        System.out         


        
22条回答
  •  太阳男子
    2020-11-21 05:57

    When you input a double number, for example, 33.33333333333333, the value you get is actually the closest representable double-precision value, which is exactly:

    33.3333333333333285963817615993320941925048828125
    

    Dividing that by 100 gives:

    0.333333333333333285963817615993320941925048828125
    

    which also isn't representable as a double-precision number, so again it is rounded to the nearest representable value, which is exactly:

    0.3333333333333332593184650249895639717578887939453125
    

    When you print this value out, it gets rounded yet again to 17 decimal digits, giving:

    0.33333333333333326
    

提交回复
热议问题