Jazerix
Jazerix

Reputation: 4801

Converting large scientific number to long

I've spend a long time now, trying to convert the number 1.2846202978398e+19 in java, without any luck. Currently what I'm trying to do (long)Double.parseDouble(hashes), however this gives 9223372036854775807, which is obviously incorrect. The actual number should look something like this 12855103593745000000.

Using int val = new BigDecimal(stringValue).intValue(); returns -134589568 as it's unable to hold the result. Switching the code to long val = new BigDecimal(hashes).longValue(); gives me -5600541095311551616 which is also incorrect.

I'm assuming this is happening due to the size of a double compared to a long.

Any ideas?

Upvotes: 3

Views: 9340

Answers (3)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

Did you try to use String.format :

String result = String.format("%.0f", Double.parseDouble("1.2846202978398e+19"));
System.out.println(result);

Output

12846202978398000000

Edit

Why you don't work with BigDecimal to do the arithmetic operations, for example :

String str = "1.2846202978398e+19";
BigDecimal d = new BigDecimal(str).multiply(BigDecimal.TEN);
//                                 ^^^^^^^^------example of arithmetic operations


System.out.println(String.format("%.0f", d));
System.out.println(String.format("%.0f", Double.parseDouble(str)));

Output

128462029783980000000
12846202978398000000

Upvotes: 5

bradimus
bradimus

Reputation: 2523

Your value exceeds the maximum size of long. You can not use long in this situation. Try

BigDecimal value = new BigDecimal("1.2846202978398e+19");

After that, you can call

value.toBigInteger()

or

 value.toBigIntegerExact()

if needed.

Upvotes: 4

Viktor Mellgren
Viktor Mellgren

Reputation: 4506

What about:

System.out.println(new BigDecimal("1.2846202978398e+19").toBigInteger());

Upvotes: 0

Related Questions