** * Constructs a new {@code BigDecimal} instance from the 64bit double * {@code val}. The constructed big decimal is equivalent to the given * double. For example, {@code new BigDecimal(0.1)} is equal to {@code * 0.1000000000000000055511151231257827021181583404541015625}. This happens * as {@code 0.1} cannot be represented exactly in binary. * <p> * To generate a big decimal instance which is equivalent to {@code 0.1} use * the {@code BigDecimal(String)} constructor. * * @param val * double value to be converted to a {@code BigDecimal} instance. * @throws NumberFormatException * if {@code val} is infinity or not a number. */ public BigDecimal(double val) { if (Double.isInfinite(val) || Double.isNaN(val)) { throw new NumberFormatException("Infinity or NaN: " + val); } long bits = Double.doubleToLongBits(val); // IEEE-754 long mantissa; int trailingZeros; // Extracting the exponent, note that the bias is 1023 scale = 1075 - (int)((bits >> 52) & 0x7FFL); // Extracting the 52 bits of the mantissa. mantissa = (scale == 1075) ? (bits & 0xFFFFFFFFFFFFFL) << 1 : (bits & 0xFFFFFFFFFFFFFL) | 0x10000000000000L; if (mantissa == 0) { scale = 0; precision = 1; } // To simplify all factors '2' in the mantissa if (scale > 0) { trailingZeros = Math.min(scale, Long.numberOfTrailingZeros(mantissa)); mantissa >>>= trailingZeros; scale -= trailingZeros; } // Calculating the new unscaled value and the new scale if((bits >> 63) != 0) { mantissa = -mantissa; } int mantissaBits = bitLength(mantissa); if (scale < 0) { bitLength = mantissaBits == 0 ? 0 : mantissaBits - scale; if(bitLength < 64) { smallValue = mantissa << (-scale); } else { BigInt bi = new BigInt(); bi.putLongInt(mantissa); bi.shift(-scale); intVal = new BigInteger(bi); } scale = 0; } else if (scale > 0) { // m * 2^e = (m * 5^(-e)) * 10^e if(scale < LONG_FIVE_POW.length && mantissaBits+LONG_FIVE_POW_BIT_LENGTH[scale] < 64) { smallValue = mantissa * LONG_FIVE_POW[scale]; bitLength = bitLength(smallValue); } else { setUnscaledValue(Multiplication.multiplyByFivePow(BigInteger.valueOf(mantissa), scale)); } } else { // scale == 0 smallValue = mantissa; bitLength = mantissaBits; } }