当前页面: 开发资料首页 → J2SE 专题 → 关于System.out.println()打印浮点数的一个小问题
关于System.out.println()打印浮点数的一个小问题
摘要: 关于System.out.println()打印浮点数的一个小问题
System.out.println(0.02); //打印结果为0.02
System.out.println(0.002); //打印结果为0.0020
为啥第二种方式最后会多一个0啊??????
不太清楚,关注一下!
println函数重载了float 和 double类型的输入处理,
0.02以float处理,所以输出就是0.02
0.002以double处理,所以输出 是0.0020
为了验正,可以把上面的程序修改为:
float f=0.02f;
double db=0.002;
System.out.println(f);
System.out.println(db);
输出的结果分别为
0.02
0.0020
感觉楼上的说了和没说一样
嗯,楼上说的没错..主要是系统会自动识别各个类型的位数..所以不用强制转化..
他最后多一个0很讨厌啊,怎么去掉啊
System.out.println(0.002f);
结果也是0.0020,楼上没找出原因啊。
继续关注!
如果想去掉的化,只有用format了!
format
方法之一
继续关注中!
用System.our.printf()
晕,是System.out.printf()
汗楼上的。。。请教jdk哪个版本的???
应该是format来做吧。。。
关注下
好象有一个什么函数,可以这样做。
转化成string,再输出
楼上, 转化string 后在输出好办法
转型为Sting再输出
System.out.println(String.valueOf(db).substring(0,5));
double i = 0.002;
System.out.printf("%4.3f",i);
不过要jdk5.0
jdk5.0 引入了System.out.printf,方便c语言程序员(强市场啊)
若是JDK5.0,用楼上的方法就行了吧(没用过)
用DecimalFormat的话:
DecimalFormat format = (DecimalFormat) NumberFormat.getInstance();
format.applyPattern("#.###############");//小数点后#的个数表示小数的截取位数
//若实际的小数位数比较小,则保留
System.out.print(format.format(-0.002));
DecimalFormat的用法示例(摘自The Java Developers Almanac 1.4):
// The 0 symbol shows a digit or 0 if no digit present
NumberFormat formatter = new DecimalFormat("000000");
String s = formatter.format(-1234.567); // -001235
// notice that the number was rounded up
// The # symbol shows a digit or nothing if no digit present
formatter = new DecimalFormat("##");
s = formatter.format(-1234.567); // -1235
s = formatter.format(0); // 0
formatter = new DecimalFormat("##00");
s = formatter.format(0); // 00
// The . symbol indicates the decimal point
formatter = new DecimalFormat(".00");
s = formatter.format(-.567); // -.57
formatter = new DecimalFormat("0.00");
s = formatter.format(-.567); // -0.57
formatter = new DecimalFormat("#.#");
s = formatter.format(-1234.567); // -1234.6
formatter = new DecimalFormat("#.######");
s = formatter.format(-1234.567); // -1234.567
formatter = new DecimalFormat(".######");
s = formatter.format(-1234.567); // -1234.567
formatter = new DecimalFormat("#.000000");
s = formatter.format(-1234.567); // -1234.567000
// The , symbol is used to group numbers
formatter = new DecimalFormat("#,###,###");
s = formatter.format(-1234.567); // -1,235
s = formatter.format(-1234567.890); // -1,234,568
// The ; symbol is used to specify an alternate pattern for negative values
formatter = new DecimalFormat("#;(#)");
s = formatter.format(-1234.567); // (1235)
// The ' symbol is used to quote literal symbols
formatter = new DecimalFormat("'#'#");
s = formatter.format(-1234.567); // -#1235
formatter = new DecimalFormat("'abc'#");
s = formatter.format(-1234.567); // -abc1235
fytain() 的方法绝。ding~~~~~~~~~`