Formatting a String to Remove Scientific Notation

2020-03-02 05:36发布

问题:

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?

回答1:

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

}


回答2:

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


回答3:

NumberFormat format = new DecimalFormat("0.############################################################");
System.out.println(format.format(Math.ulp(0F)));
System.out.println(format.format(1F));


回答4:

The float doesn't contain an e, that is just how it is being displayed to you. You can use DecimalFormat to change how it is displayed.

http://ideone.com/jgN6l

java.text.DecimalFormat df = new java.text.DecimalFormat("#,###.######################################################");
System.out.println(df.format(res));

You will notice some odd looking numbers though, due to floating point.