在小数点后面为什么两个零不在双精度中考虑。

huangapple go评论76阅读模式
英文:

after decimal why twoo zeros not consider in double

问题

private static DecimalFormat df = new DecimalFormat("0.00");

public static void main(String[] args) {
    double input = 300.00;

    System.out.println("double : " + input);

    Double d = Double.valueOf(df.format(input));
    System.out.println("##1::" + d);
    System.out.println("##2 ::" + df.format(input));
    System.out.println("##3 ::" + Double.valueOf(df.format(input)));
}
}

Output:

double : 300.0 
##1::300.0 
##2 ::300.00 
##3 ::300.0 
英文:
private static DecimalFormat df = new DecimalFormat("0.00");

    public static void main(String[] args) {
        double input = 300.00;

        System.out.println("double : " + input);
       
        Double d=Double.valueOf(df.format(input));
       System.out.println("##1::"+d);
       System.out.println("##2 ::"+df.format(input));
       System.out.println("##3 ::"+Double.valueOf(df.format(input)));	        
    }
}

Output:

double : 300.0 
##1::300.0 
##2 ::300.00 
##3 ::300.0 

Expected output: 300.00

答案1

得分: 2

你可以使用BigDecimal来进行精度控制和四舍五入的操作。尝试以下代码:

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Test {

    public static void main(String[] args) {
        BigDecimal input = BigDecimal.valueOf(300);

        System.out.println("double 2 digit: " + Test.round(input, 2));
        System.out.println("double 5 digit: " + Test.round(input, 5));
    }

    public static BigDecimal round(BigDecimal bd, int scale) {
        return bd.setScale(scale, RoundingMode.HALF_UP);
    }
}

输出如下:

double 2 digit: 300.00
double 5 digit: 300.00000
英文:

You can use BigDecimal for scale and round double. Try this :

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Test {

    public static void main(String[] args) {
        BigDecimal input = BigDecimal.valueOf(300);

        System.out.println("double 2 digit: " + Test.round(input, 2));
        System.out.println("double 5 digit: " + Test.round(input, 5));
    }

    public static BigDecimal round(BigDecimal bd, int scale) {
        return bd.setScale(scale, RoundingMode.HALF_UP);
    }
}

Output like this :

double 2 digit: 300.00
double 5 digit: 300.00000

huangapple
  • 本文由 发表于 2020年5月30日 04:37:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/62094241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定