gpt4 book ai didi

java - 解析双数和百万

转载 作者:行者123 更新时间:2023-12-01 09:05:44 26 4
gpt4 key购买 nike

我有一个文件,它代表数百万个数字(如29.879.999)和双数(如28.09)。我正在尝试使用 NumberFormat 解析它们,并将它们全部(整数和 double )转换为 double。这是我写的:

for (String[] entry : data) {
NumberFormat nf = NumberFormat.getInstance();
Number value = nf.parse(entry[4]).doubleValue();
System.out.println("closingvalue: "+value);
}

结果是:

closingvalue  2925.0
closingvalue 2.9879999E7
closingvalue 2809.0
closingvalue 2.7219999E7
closingvalue 2.5969999E7
closingvalue 2491.0
closingvalue 2635.0
closingvalue 2591.0

输入文件是这样的:

Date;Open;High;Low;Close;Log Return
2/1/2009;31.190.001;31.639.999;30.469.999;31.35;-
5/1/2009;30.73;30.77;29.08;29.25;-0.0693
6/1/2009;29.790.001;30.42;29.51;29.879.999;0.0213
7/1/2009;29.15;29.40;28.00;28.09;-0.0618
8/1/2009;27.90;27.950.001;26.860.001;27.219.999;-0.0315

我想将它们全部解析为 double 就像 28.09 甚至数百万。感谢任何帮助。谢谢!

最佳答案

假设以下是有效格式

contains decimals
0.<any number>
-0.<any number>
1.234.567.89 (last third digit is ".")

all others are integers.

那么您所要做的就是将 3 位小数条件更改为“,”。这会将您的号码更改为

0,<any number>
-0,<any number>
1.234.567,89 (last third digit is now ",")

并使用 Locale.GERMANY 进行解析

NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
Double parsedNumber = nf.parse(value[4]).doubleValue();

编辑:这就是我转换小数的方法。

String testString = value[4];
if(testString.size() >= 3){ //must be at least 3 digits
int last3rdPosition = testString.size() - 3;

if(testString.charAt(last3rdPosition) == '.'){

//check if the last third char is "."
//handle cases like 31.35 (change it to 31,35)
testString.setChar(last3rdPosition, ',');
} else if (testString.charAt(0) == '0'
&& testString.charAt(1) == '.'){

//handle cases like 0.0213 (change it to 0,0213)
testString.setChar(1, ',')
}else if (testString.charAt(0) == '-'
&& testString.charAt(1) == '0'
&& testString.charAt(2) == '.'){

//handle cases like -0.0315 (change it to -0,0315)
testString.setChar(2, ',')
}

}
// do converting as per normal using Locale.GERMANY
// Locale.GERMANY will treat "." as the thousands separator
// and "," as the decimal separator
NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
Double parsedNumber = nf.parse(testString).doubleValue();

关于java - 解析双数和百万,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41301262/

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