7

Possible Duplicate:
Rounding in java Float.parseFloat

I want to convert strings to float i say:

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

Output:

1553782.0

I say:

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

Output:

1553782.0

How to get Float without lossing precision?

2
  • use Double instead of Float Commented Dec 26, 2012 at 7:08
  • 1
    Keep in mind that floating point values are approximate, not exact. "1553781.9999999999" would become 1553782. Commented Dec 26, 2012 at 7:11

4 Answers 4

7

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

float has a limitation of smaller size (4 bytes) so it's not good for big decimals, double has the double size (8 bytes)

Sign up to request clarification or add additional context in comments.

Comments

5

If you are looking for accuracy, I would suggest BigDecimal

This is just like normal wrapper class which provides methods for all your operations. And yes it takes argument as String as well.

  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

2 Comments

if i will use BigDecimal i need to convert it in float later to work with it like with float type? I mean im already have classes works with float types i gonna remake it to work with BigDecimal?
You can perform all float operations with BigDecimal as well. So will suggest; replace float with BigDecimal.
2

You cannot use float or double without a risk of losing precision. First of all their precision is limited, for float it is approx 7-8 decimal digits, for double ~16 digits. Apart from that Java floating points types are binary internally so they cannot store some decimal fractions without losing precision. If you really need exact decimal fractions use java.math.BigDecimal. Read "Effective Java" Item 48: "Avoid float and double if exact answers are required".

5 Comments

if i will use BigDecimal i need to convert it in float later to work with it like with float type? I mean im already have classes works with float types i gonna remake it to work with BigDecimal?
You can convert it to float or double when necessary as bd.floatValue() or db.doubleValue() if need be. But you also can work with it as BigDecimal, it has all necessary arithmetic.
But if ill convet bd in float i lose precision?
Yeah ill try convert db in float and it rounds. But thanks for answer)
Sure, it all depends, floats are short and fast, but you just need to be aware that accurracy is not gearanteed, even with doubles. See my update about "Effective Java"
0

Instead of Float you can use Double

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.