系统输出java程序中的双数字输出

时间:2012-03-22 11:25:56

标签: java string java-io

我有一个程序,我通过根据条件从文件中添加几个输入价格来生成两个双号。

String str;
double one = 0.00;
double two = 0.00;
BufferedReader in = new BufferedReader(new FileReader(myFile));

while((str = in.readLine()) != null){
     if(str.charAt(21) == '1'){
         one += Double.parseDouble(str.substring(38, 49) + "." + str.substring(49, 51));
     }

     else{
         two += Double.parseDouble(str.substring(38, 49) + "." + str.substring(49, 51));
     }
   }

in.close();
System.out.println("One: " + one);
System.out.println("Two: " + two);      

输出如下:

One: 2773554.02
Two: 6.302505836000001E7

问题:

其中没有任何输入包含超过两位小数。一和二的计算方式完全相同。

那么为什么输出格式是这样的。

我期待的是:

One: 2773554.02
Two: 63025058.36

为什么打印有两种不同的格式?我想再次将输出写入文件,因此十进制后必须只有两位数。

1 个答案:

答案 0 :(得分:1)

使用double导致缺少准确性的问题。使用BigDecimal来避免这种情况。

要进行打印,请使用DecimalFormat,如下所示:

DecimalFormat format = new DecimalFormat("0.##");
System.out.println("One: " + format.format(one));
System.out.println("Two: " + format.format(two));

DecimalFormat的文档:http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html