Retain precision with double in Java

前端 未结 22 3152
情歌与酒
情歌与酒 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 06:12

    Floating point numbers differ from real numbers in that for any given floating point number there is a next higher floating point number. Same as integers. There's no integer between 1 and 2.

    There's no way to represent 1/3 as a float. There's a float below it and there's a float above it, and there's a certain distance between them. And 1/3 is in that space.

    Apfloat for Java claims to work with arbitrary precision floating point numbers, but I've never used it. Probably worth a look. http://www.apfloat.org/apfloat_java/

    A similar question was asked here before Java floating point high precision library

提交回复
热议问题