How to Convert Exponential Form of a number to Decimal Form in java

In Java you will see that most of the value are displayed in Exponential form while using Doubles and Long.


Example:
In following we are multiplying 4.58 with 10000 and the result is printed.
Double a = 4.58d / 10000;
System.out.println( a.doubleValue());
 
a = 2.85d * 100000000;
System.out.println( a.doubleValue());
Result:
4.58E-4
 4.58E8
You can do this simply by using class java.math.BigDecimal. In following example we are using BigDecimal.valueOf() to convert the Double value to BigDecimal and than .toPlainString() to convert it into plain decimal string.

import java.math.BigDecimal;
Double a = 4.58d / 10000;
System.out.println(BigDecimal.valueOf(a).toPlainString());
 a = 4.58d * 100000000;
System.out.println(BigDecimal.valueOf(a).toPlainString());
Result:
0.000458 
458000000

No comments:

Post a Comment

Please Provide your feedback here