代码如下,java用BigDecimal四舍五入怎么还有问题呀?哪种方式是完全没有问题的?
ringa_lee
ringa_lee 2017-04-18 10:51:52
0
2
741

1.为什么不是1.51?输出的是1.50

2.decimalformat括号里的字符串代表了什么意思?有模板吗?如果是别的格式应该怎么写

3.为什么要用#号而不是0.00?如果是#好的话,当a是0.505的时候有bug

        double a =1.505;
        BigDecimal bd = new BigDecimal(a);
        System.out.println(new DecimalFormat("#.00").format(bd));
ringa_lee
ringa_lee

ringa_lee

reply all(2)
小葫芦

First of all, point out a problem: construction BigDecimal 的时候,尽量不要使用浮点数(doublefloat), because there is a lack of precision in the storage of floating point numbers in computers. For example, the code you wrote:

public static void main(String[] args) throws Exception {
    double a = 1.505;
    BigDecimal bd = new BigDecimal(a);

    System.out.println("bd: " + bd.toString());
}

Run results:

You can see that the floating point number 1.505 cannot be stored in the computer - if you don’t know the specific reason, please search for it yourself "The problem of missing precision of floating point numbers"


Second, if you need to output 1.51, which is often called "rounding", then you need to specify the rounding mode of DecimalFormat:

public static void main(String[] args) throws Exception {
    BigDecimal bd = new BigDecimal("1.505");
    System.out.println("bd: " + bd.toString());

    DecimalFormat df = new DecimalFormat("#.00");
    df.setRoundingMode(RoundingMode.HALF_UP);

    System.out.println("format: " + df.format(bd));
}

Run results:

If you don’t understand the usage of RoundingMode, please search for "Usage of RoundingMode"


Third, regarding the meaning of the DecimalFormat strings in brackets, please search "Usage of DecimalFormat"

伊谢尔伦
    System.out.println(String.format("%.2f", a));
    System.out.println(new Formatter().format("%.2f", a));
    
    这两种是可以的。
  
  double d = 5.505;
  System.out.println(d)
  输出的是1.504xxxxxxxxx,所以java在做四舍五入的时候舍掉了后面的4xxxxxx。
  
  
  等待大神解答
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template