Java 浮点数输出格式(四舍五入)

http://oracle-9i.iteye.com/blog/1103316

double四舍五入得到精确结果:

double a = -12.4658;
double b = -12.5658;

System.out.println((int) Math.floor(a));
System.out.println((int) Math.ceil(b));
System.out.println(new BigDecimal(a).setScale(0, BigDecimal.ROUND_HALF_UP));
System.out.println(new BigDecimal(b).setScale(0, BigDecimal.ROUND_HALF_UP));

注:一般double型不适合初始化BigDecimal(最好用String类型的),但要输出四舍五入最好用BigDeicmal的输出格式,因为BigDecimal的有效数字大于16.

结果:

-13
-12
-12
-13

 

1)System.out.printf("",) 这个有的地方有输出格式错误,但大多数地方还是可以的

 import java.math.*;

import java.util.*;

import java.text.*;

2)http://g.kehou.com/t1018145137.html

例子:

System.out.println(Math.ceil(123.456));
System.out.println(Math.floor(123.456));
System.out.println(Math.round(123.456));
System.out.println(Math.round(123.456 / .01) * .01);
System.out.println(Math.round(123.456 / 10) * 10);
System.out.println(Math.round(122.45 / 5) * 5);

DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(123.456));

DecimalFormat df1 = new DecimalFormat("-0.00");
System.out.println(df1.format(123.456));

DecimalFormat df2 = new DecimalFormat(",000.#");
System.out.println(df2.format(12345.05));
System.out.println(df2.format(123.456));

// #: 后面没数字 ,0也代表没有。 0: 超出范围按原来的输出,不够补零
DecimalFormat df3 = new DecimalFormat("#,###");
System.out.println(df3.format(12345.6));

DecimalFormat df4 = new DecimalFormat("0.00%");
System.out.println(df4.format(123.456));

DecimalFormat df5 = new DecimalFormat("0.000E00");
System.out.println(df5.format(1234.56));

DecimalFormat df6 = new DecimalFormat("0.00\u2030");
System.out.println(df6.format(123.4567));

 

输出:

124.0
123.0
123
123.46000000000001
120
120
123.46
-123.46
12,345
123.5
12,346
12345.60%
1.235E03
123456.70‰

 

3)http://blog.csdn.net/ghychina/article/details/7556197

BigDecimal f2 = new BigDecimal("12.56").setScale(0, BigDecimal.ROUND_HALF_UP);
System.out.println(f2);

 

4)http://www.blogjava.net/jzone/articles/292581.html

例子:

System.out.println((int) Math.rint(2.5));


System.out.println((int) Math.rint(2.51));

System.out.println(new DecimalFormat("0").format(1234.56));

for (int i = 0; i < 10; i++) {
System.out.println(Math.random() + " " + new Random().nextDouble() + " " + new Random().nextBoolean());
}

结果:

2
3
1235
0.21112804862552115 0.22463215060969088 false
0.632170890240952 0.23340358003260187 true
0.279415739588288 0.702832475646666 false
0.10463516134365447 0.8008920181649813 false
0.3483970844364095 0.9275524624734964 true
0.04358678634031876 0.07910617091419747 true
0.18868018082404936 0.02508782117927366 true
0.853959812163814 0.8019206525506904 true
0.20117519818929142 0.8022293645731935 true
0.7455301430762435 0.9085165602651166 false

 

posted on 2013-02-24 19:28  Sure_Yi  阅读(1670)  评论(0编辑  收藏  举报

导航