Pages Navigation Menu

Coding is much easier than you think

Convert Exponential form to Decimal number format in Java

 
 
In Java you will see that most of the values are displayed in Exponential form while using Doubles and Long.
 
Example:
In the following example we are multiplying/dividing 7.35 with 1000000000 and following result is printed.
 

//Multiplication example
Double a = 7.35d * 1000000000;
System.out.println(a.doubleValue());

 

Result:
7.35E9

 

//Division example
Double a = 7.35d / 100000;
System.out.println("1) " + a.doubleValue());

 

Result:
7.35E-5

 
Thus you can see the result is printed in exponential format. Suppose if you want to display the result in pure decimal format like: 0.0000735 or 7350000000. 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 then .toPlainString() to convert it into plain decimal string.
 
Example….
 

package com.simplecode.java;
import java.math.BigDecimal;

class BigDeci {
	public static void main(String ar[])
	{
		Double digit = 7.35d / 100000;
		System.out.println("1. " + BigDecimal.valueOf(digit).toPlainString());
		digit = 7.35d * 100000000;
		System.out.println("2. " + BigDecimal.valueOf(digit).toPlainString());
	}
}

 

Result:

1. 0.0000735
2. 735000000

 
The disadvantage of the above method is that it generates long strings of number. Suppose if in case you want to restrict the value and round off the number to 5 or 6 decimal point, then you can use java.text.DecimalFormat class. In following example we are rounding off the number to 4 decimal points and printing the output.
 


package com.simplecode.java;

import java.text.DecimalFormat;

class BigDeci {
	public static void main(String ar[])

	{
		Double digit = 7.35d / 100000;
		DecimalFormat formatter = new DecimalFormat("0.0000");
		System.out.println(formatter .format(digit));
	}
}

 

Result :
0.0001