Formatting a String to Remove Scientific Notation - Java

只谈情不闲聊 提交于 2019-11-30 20:26:17
dharam

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

}

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;
}
NumberFormat format = new DecimalFormat("0.############################################################");
System.out.println(format.format(Math.ulp(0F)));
System.out.println(format.format(1F));

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!