-4

When I tyr to convert a String "95941634.164" to a float and print the same, it is printing as 9.5941632E7 but not as 95941634.164.

I tried following conversion methods Float.parseFloat() and Float.valueOf()

public static void main(String args[])
{
    String s = "95941634.164" ;
    Float f  = Float.valueOf(s);
    System.out.println(f);
    System.out.println(Float.parseFloat("95941634.164"));
}

Actual: 9.5941632E7 expected 95941634.164

anil
  • 5
  • Hi anil, you might want to look at this existing question https://stackoverflow.com/questions/6713673/precision-error-with-floats-in-java . Some languages are notorious for their precision on Floats. – P Fuster Jun 11 '19 at 10:29
  • If you want to keep the accuracy you should use BigDecimal: BigDecimal b = new BigDecimal("95941634.164"); – Joachim Rohde Jun 11 '19 at 10:33

3 Answers3

4

The nearest Float to 95941634.164 is 95941632.

And Java is using scientific notation to output that value.

Given that the nearest Double to your number is 95941634.1640000045299530029296875, you might have more tractable output if you use a Double. But if you want exact decimal results then use a decimal type: BigDecimal for example.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

You can try String.format with cast to double. Here is an example :

public static void main(String args[])
{
    String s = "95941634.164" ;
    Float f= Float.parseFloat(s);
    Double d  = Double.parseDouble(s);
    System.out.println(String.format("%.3f", f));
    System.out.println(String.format("%.3f", d));
}

The format rounds off while using float but not for double. Here is the output :

95941632.000                                                                                                                            
95941634.164 
-1

You could use printf() with %f:

System.out.printf("value: %f\n", f);
Anjana
  • 903
  • 1
  • 5
  • 13
  • the problem is not here, the problem is the number of bits in the mantissa of a _float_ – bruno Jun 11 '19 at 15:21