Java中Double保留後小數字的幾種方法

2021-08-18 03:09:47 字數 1233 閱讀 4702

1.能四捨五入

1

double d = 114.145;

2 d = (double) math.round(d * 100) / 100;

3 system.out.println(d);

2. bigdecimal.round_half_up表示四捨五入,bigdecimal.round_half_down也是五舍六入,bigdecimal.round_up表示進製處理(就是直接加1),bigdecimal.round_down表示直接去掉尾數。

1

double d = 114.145;

2 bigdecimal b = new

bigdecimal(d);

3 d = b.setscale(2, bigdecimal.round_half_up).doublevalue();

4 system.out.println(d);

1.#.00表示保留後兩位,它的處理方式是直接截掉不要的尾數,不四捨五入。

1

double d = 114.145;

2 decimalformat df = new decimalformat("#.00");

3 string str =df.format(d);

4 system.out.println(str);

2.%.2f表示保留後兩位,它的處理方式也是直接截掉不要的尾數,不四捨五入。

1

double d = 114.145;

2 string.format("%.2f", d);

3.roundingmode.half_down表示 五舍六入,負數先取絕對值再五舍六入再負數,roundingmode.half_up:表示四捨五入,負數先取絕對值再五舍六入再負數。

1

double d = 114.145

2 numberformat nf =numberformat.getnumberinstance();3//

保留兩位小數

4 nf.setmaximumfractiondigits(2); 5//

如果不需要四捨五入,可以使用roundingmode.down

6nf.setroundingmode(roundingmode.up);

7 system.out.println(nf.format(d));

Java中Double保留後小數字的幾種方法

1.能四捨五入 double d 114.145 d double math.round d 100 100 system.out.println d 2.bigdecimal.round half up表示四捨五入,bigdecimal.round half down也是五舍六入,bigdecim...

Double保留後小數字的方法

1.使用math類的round方法 能四捨五入 double d 114.145 d double math.round d 100 100 system.out.println d 2.使用bigdecimal類 表示四捨五入,也是五舍六入,表示進製處理 就是直接加1 表示直接去掉尾數。doubl...

Java中對double型別保留兩位小數的方法

整理了網上一些方法,方便以後查閱。1.使用bigdecimal類 bigdecimal b1 new bigdecimal width bigdecimal b2 new bigdecimal height bigdecimal b3 b1.multiply b2 return b3.setscal...