格式化字符串以删除科学记数法 - Java [英] Formatting a String to Remove Scientific Notation - Java
问题描述
我有下面的代码拆分了一串数字(用空格分隔),然后创建一个浮点数组:
//分割字符串,然后用值创建一个浮点数组。
String [] tabOfFloatString = value.split();
int length = tabOfFloatString.length;
System.out.println(float string的长度是+ length);
float [] floatatsArray = new float [length];
for(int l = 0; l float res = Float.parseFloat(tabOfFloatString [l]);
System.out.println(Float is+ res);
floatsArray [l] = res;
$ b 问题在于字符串中的某些值用科学记数法格式化 - 例如,他们阅读-3.04567E-8。
我想要做的是以不包含E号码的浮点数结束。
我一直在阅读这个线程,这表明我可以使用BigDecimal,但是我无法得到这个工作 - 这是最好的办法还是应该尝试别的? 如何转换字符串3.0103 E-7到0.00000030103在Java?
解决方案下面是你的代码稍作修改。按照我的说法,这样做效果不错,实际上并不关心指数的顺序:
pre $ public void function(){
String value =123456.0023 -3.04567E-8 -3.01967E-20;
String [] tabOfFloatString = value.split();
int length = tabOfFloatString.length;
System.out.println(float string的长度是+ length);
float [] floatatsArray = new float [length];
for(int l = 0; l String res = new BigDecimal(tabOfFloatString [l])。toPlainString();
System.out.println(Float is+ res);
floatsArray [l] = Float.parseFloat(res);
}
}
I have the following code which splits a string of numbers (separated by a space) and then creates an array of floats :
//Split the string and then build a float array with the values.
String[] tabOfFloatString = value.split(" ");
int length = tabOfFloatString.length;
System.out.println("Length of float string is" + length);
float[] floatsArray = new float[length];
for (int l=0; l<length; l++) {
float res = Float.parseFloat(tabOfFloatString[l]);
System.out.println("Float is " + res);
floatsArray[l]=res;
}
The problem is that some of the values in the string are formatted with scientific notation - e.g they read -3.04567E-8.
What I want to do is end up with a float which does not contain the E number.
I have been reading this thread which suggests that I could use BigDecimal, however am unable to get this to work - is this the best approach or should I try something else ? How to convert a string 3.0103E-7 to 0.00000030103 in Java?
Below is your code slightly modified. As per me this works well and doesn't actually cares he order of the exponents:
public void function() {
String value = "123456.0023 -3.04567E-8 -3.01967E-20";
String[] tabOfFloatString = value.split(" ");
int length = tabOfFloatString.length;
System.out.println("Length of float string is" + length);
float[] floatsArray = new float[length];
for (int l = 0; l < length; l++) {
String res = new BigDecimal(tabOfFloatString[l]).toPlainString();
System.out.println("Float is " + res);
floatsArray[l] = Float.parseFloat(res);
}
}
这篇关于格式化字符串以删除科学记数法 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!