日期:2014-05-20  浏览次数:20754 次

烦人的double问题
如下面代码测试,程序输出
a:   39.199999999999996
b:   8.93
怎么能让a的值是39.20?

public   class   TestDouble   {

public   void   testDouble(){
double   a   =   43.12   -   3.92;
double   b   =   12.01   -   3.08;
System.out.println( "a:   "   +   a);
System.out.println( "b:   "   +   b);

}
public   static   void   main(String[]   args){
TestDouble   d   =   new   TestDouble();
d.testDouble();
}

}

谢谢!


------解决方案--------------------
给你一个提示,四舍五入
------解决方案--------------------
public class test {

public void testDouble(){
double a = 43.12 - 3.92;
double b = 12.01 - 3.08;
java.text.DecimalFormat df = new DecimalFormat( "#.00 ");
System.out.println( "a: " + df.format(a));
System.out.println( "b: " + df.format(b));

}
public static void main(String[] args){
test d = new test();
d.testDouble();
}
------解决方案--------------------
很简单啊,用java.text包就可以了

import java.text.DecimalFormat;
public class TestDouble {

public void testDouble(){
double a = 43.12 - 3.92;
double b = 12.01 - 3.08;
System.out.println( "a: " + TestDouble.formatDecimal(a, "#.00 "));
System.out.println( "b: " + b);

}
public static void main(String[] args){
TestDouble d = new TestDouble();
d.testDouble();
}



/**
* 根据格式得到格式化的浮点型数字
* @param data 要格式化的数字,类型为double
* @param type 格式类型,如#,###.00
* @return String 返回String类型的数值,形式如:23,345,445.34
*/
public static String formatDecimal(double data, String type) {
DecimalFormat dFormat = new DecimalFormat(type);
return dFormat.format(data);
}

}