Levvy
Levvy

Reputation: 1150

Java String parseFloat or double for x.xxxxxx numbers?

I have numbers in String like:

"34.556231"
"43.385644"
"65.659388"

with six decimals after dot.

I want to parse them to Float or eventually Double.

How to convert these Strings to Float or Double?

When I use Float.parseFloat("5.586905") then the float value is equal 5.58691 so it looks like its parsing to only 5 decimal places and rounds it.

How to resolve it?

Upvotes: 1

Views: 1053

Answers (2)

SpringLearner
SpringLearner

Reputation: 13854

If you have more numbers after decimal then you can use bigdecimal like this

String x="5.586905";
    BigDecimal b=new BigDecimal(x);
            double value=b.doubleValue()            ;
    System.out.println(value);

but as per your given number Double.parseDouble() is enough

Upvotes: 0

k_g
k_g

Reputation: 4463

float doesn't have enough precision to store the number you are giving it. Use double instead.

As the java specs say,

As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers

In other words, don't use float unless storage is a major concern. It is much less precise than double and will lead to ridiculous results like the one you just outlined.

Use Double.parseDouble.

Upvotes: 1

Related Questions