gpt4 book ai didi

java - 添加文本文件中的值

转载 作者:行者123 更新时间:2023-12-02 00:18:47 25 4
gpt4 key购买 nike

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

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

最佳答案

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)));
}
}

关于java - 添加文本文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11410054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com