java.math.BigInteger doubleValue()
Description
On this document we will be showing a java example on how to use the doubleValue() method of BigInteger Class. Basically this method converts this BigInteger to a double. This conversion is similar to the narrowing primitive conversion from double to float as defined in section 5.1.3 of The Java™ Language Specification: if this BigInteger has too great a magnitude to represent as a double, it will be converted to Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY as appropriate. Since the BigInteger can hold higher precision, when we do conversion to double value at some point we will lose some precision.
For reference the byte range is from 4.9E-324 to 1.7976931348623157E308 and these information is readily available through the Double constants Double.MIN_VALUE and Double.MAX_VALUE.
Method Syntax
public double doubleValue()
Method Argument
Data Type | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns
The doubleValue() method returns this BigInteger converted to a double.
Compatibility
Requires Java 1.1 and up
Java BigInteger doubleValue() Example
Below is a java code demonstrates the use of doubleValue() method of BigInteger class. The example presented might be simple however it shows the behavior of the doubleValue() method.
package com.javatutorialhq.java.examples; import java.math.BigInteger; import java.util.Scanner; /* * A java example source code to demonstrate * the use of doubleValue() method of BigInteger class */ public class BigIntegerDoubleValueExample { public static void main(String[] args) { // Declare and initialize our BigInteger values BigInteger val1 = new BigInteger("12"); BigInteger val2 = new BigInteger("56554564564564578"); // get the double value of each BigInteger double doubleVal1 = val1.doubleValue(); double doubleVal2 = val2.doubleValue(); // print the operation System.out.println("val1 in double is "+doubleVal1); System.out.println("val2 in double is "+doubleVal2); } }
This example is a lot simpler than it looks. We only initialize two BigInteger values, one that we know is in range of double and the other is outside the range. The result of the doubleValue is printed out.