[英]Converting string to floating point creates an unanticipated return. Java
I have a 2d array which was created by parsing data in a file. 我有一个二维数组,它是通过解析文件中的数据创建的。 The method sends each part of data to a string. 该方法将数据的每个部分发送到字符串。 I am trying to convert the array from strings to floating point. 我试图将数组从字符串转换为浮点数。 Everything prints alright except for one column. 除一列外,其他所有内容均可正常打印。
For example: 例如:
2015/10/21,113.7600,42276880.0000,114.0000,115.5800,113.7000
2015/10/20,113.7700,48929200.0000,111.3400,114.1700,110.8200
2015/10/19,111.7300,29723750.0000,110.8000,111.7500,110.1100
Converts to: 转换为:
0.0 113.76 4.227688E7 114.0 115.58 113.7
0.0 113.77 4.89292E7 111.34 114.17 110.82
0.0 111.73 2.972375E7 110.8 111.75 110.11
The date column is meant to return 0.0 but the 3rd column returns a weird response. date列应返回0.0,但第3列将返回一个奇怪的响应。 Is this an error with my code or the data? 这是我的代码或数据错误吗?
Converting string array to floating point array method 将字符串数组转换为浮点数组方法
public void createDataArray(String [] [] n){
for(int x=0;x<n.length;x++) {
for(int y=0;y<n [x].length;y++) {
switch(y) {
case 0:
dataArray[x] [y] = 0;
break;
case 1:
dataArray[x] [y] = new Float(n[x] [y]);
break;
case 2:
dataArray[x] [y] = new Float(n[x] [y]);
break;
case 3:
dataArray[x] [y] = new Float(n[x] [y]);
break;
case 4:
dataArray[x] [y] = new Float(n[x] [y]);
break;
case 5:
dataArray[x] [y] = new Float(n[x] [y]);
break;
case 6:
dataArray[x] [y] = new Float(n[x] [y]);
break;
}
}
}
}
New array printing method 新的阵列印刷方法
public void printArray() {
for(int x=0;x<dataArray.length;x++) {
for(int y=0;y<dataArray[x].length;y++) {
System.out.printf("%s ", dataArray[x] [y]);
}
System.out.println();
}
}
If you would like any more information just ask. 如果您需要更多信息,请询问。 I'm fairly certain its something wrong with the data but even after giving it fake values it still returns a similar response. 我相当确定数据有问题,但是即使为它提供了假值,它仍然会返回类似的响应。
That's scientific notation, try using %f for the floats instead of %s (string). 这是科学的表示法,请尝试将%f用作浮点数,而不是%s(字符串)。 You can get more control as necessary: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html 您可以根据需要获得更多控制权: https : //docs.oracle.com/javase/tutorial/java/data/numberformat.html
Based on your requirements, you have to use %f
for printing float/double. 根据您的要求,您必须使用%f
来打印浮点/双精度。
Example: 例:
String[] floatNumbers = {"42276880.0000", "48929200.0000","29723750.0000"};
for (String s: floatNumbers ) {
Float temp = new Float(s);
System.out.printf("%f\t", temp);
System.out.println(temp);
}
Output: 输出:
42276880.000000 4.227688E7 42276880.000000 4.227688E7
48929200.000000 4.89292E7 48929200.000000 4.89292E7
29723750.000000 2.972375E7 29723750.000000 2.972375E7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.