Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a String to Remove Scientific Notation - Java

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?

like image 236
GuybrushThreepwood Avatar asked May 09 '12 16:05

GuybrushThreepwood


2 Answers

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

}
like image 96
dharam Avatar answered Sep 22 '22 08:09

dharam


Accepted answered doesn't work for me, When do

floatsArray[l] = Float.parseFloat(res);

the Float.parseFloat(res) change non scientific anotation into scientific anotation so i had to delete it.

This one worked:

public String[] avoidScientificNotation(float[] sensorsValues)
{
     int length = sensorsValues.length;
     String[] valuesFormatted = new String[length];

     for (int i = 0; i < length; i++) 
     {
         String valueFormatted = new BigDecimal(Float.toString(sensorsValues[i])).toPlainString();
         valuesFormatted[i] = valueFormatted;
     }
    return valuesFormatted;
}
like image 30
Copper Copperone Avatar answered Sep 23 '22 08:09

Copper Copperone