从文本文件中添加值

时间:2012-07-10 09:08:55

标签: java file-io sum bufferedreader

嗨大家我有一个文本文件,其中包含每行的子串(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

金额在小数点后两位,我需要在小数点后两位的结果。实现这一目标的最佳途径是什么?

2 个答案:

答案 0 :(得分: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)));
}
}

答案 1 :(得分:1)

或者,使用String.format格式化double值。

System.out.println (String.format("%1.2f", i));