0

嗨,伙计们,我有一个文本文件,其中包含每行子字符串 (34, 47) 处的金额。我需要总结文件末尾的所有值。我有这个我已经开始构建的代码,但我不知道如何从这里开始:

public class Addup {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws FileNotFoundException, IOException {
    // TODO code application logic here
    FileInputStream fs = new FileInputStream("C:/Analysis/RL004.TXT");
    BufferedReader br = new BufferedReader(new InputStreamReader(fs));
    String line;
    while((line = br.readLine()) != null){
        String num = line.substring(34, 47);

        double i = Double.parseDouble(num);
        System.out.println(i);
    }
}
}

输出是这样的:

1.44576457E4
2.33434354E6
4.56875685E3

金额有两位小数,我也需要两位小数的结果。实现这一目标的最佳方法是什么?

4

2 回答 2

2

DecimalFormat是使用的最佳选择:

double roundTwoDecimals(double d) {
            DecimalFormat twoDForm = new DecimalFormat("#.##");
        return Double.valueOf(twoDForm.format(d));
}

您可以将代码更改为:

public static void main(String[] args) throws FileNotFoundException, IOException {
    // TODO code application logic here
    double sum = 0.0;
    FileInputStream fs = new FileInputStream("C:/Analysis/RL004.TXT");
    BufferedReader br = new BufferedReader(new InputStreamReader(fs));
    String line;
    while((line = br.readLine()) != null){
        String num = line.substring(34, 47);

        double i = Double.parseDouble(num);
        sum = sum + i;
        DecimalFormat twoDForm = new DecimalFormat("#.##");
        System.out.println(Double.valueOf(twoDForm.format(i)));
    }
        System.out.println("SUM = " + Double.valueOf(twoDForm.format(sum)));
}
}
于 2012-07-10T09:12:32.200 回答
1

或者,用于String.format格式化双精度值。

System.out.println (String.format("%1.2f", i));
于 2012-07-10T09:16:37.367 回答