String conversion for float in Java without rounding

Possible duplicate:
Rounding in java Float.parseFloat

I want to convert strings to float, I say:

System.out.println(Float.parseFloat("1553781.9829")); 

Conclusion:

 1553782.0 

I say:

 System.out.println(Float.valueOf("1553781.9829")); 

Conclusion:

 1553782.0 

How to get a float without losing accuracy?

+6
source share
4 answers

use System.out.println(Double.parseDouble("1553781.9829")); instead

float has a smaller size limit (4 bytes), so it is not suitable for large decimal places, double has a double size (8 bytes)

+7
source

If you are looking for accuracy , I would suggest BigDecimal

It is like a regular wrapper class that provides methods for all of your operations. And yes, it takes an argument as String.

  BigDecimal bd = new BigDecimal("1553781.9829"); System.out.println(" bd :"+ bd); //prints the same value 

URL: http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html

+5
source

You cannot use float or double without the risk of losing precision. First of all, their accuracy is limited, for float it is approximately 7-8 decimal digits, for double 16 digits. Besides the fact that Java floating point types are internal binary, therefore they cannot store some decimals without loss of precision. If you really need exact decimal fractions, use java.math.BigDecimal. Read Effective Java. Paragraph 48: "Avoid floating and double if accurate answers are required."

+1
source

Instead of Float you can use Double

 System.out.println(Double.valueOf("1553781.9829")); System.out.println(Double.parseDouble("1553781.9829")); 
0
source

All Articles