【问题标题】:system out output for double numbers in a java programjava程序中双数的系统输出输出
【发布时间】:2012-03-22 11:25:56
【问题描述】:

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

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

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

【问题讨论】:

标签: java string java-io


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多