Here you can find the source of toBigDecimal(Number number)
Parameter | Description |
---|---|
number | a number to be converted |
Parameter | Description |
---|---|
NumberFormatException | if the number is infinite or NaN |
public static BigDecimal toBigDecimal(Number number) throws NumberFormatException
//package com.java2s; //License from project: Open Source License import java.math.BigDecimal; import java.math.BigInteger; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; public class Main { /**// ww w . ja va 2 s .com * Returns a {@link java.math.BigDecimal} representation of a given number.<br> * If the class of a number isn't one of standard Java number classes, * the conversion is made through number doubleValue() method call.<br> * If a number is null then null is returned. * @param number a number to be converted * @return BigDecimal representation of a given number * @throws NumberFormatException if the number is infinite or NaN */ public static BigDecimal toBigDecimal(Number number) throws NumberFormatException { if (number == null) return null; if (number instanceof BigDecimal) return (BigDecimal) number; if (number instanceof Long) return BigDecimal.valueOf((Long) number); if (number instanceof Integer) return BigDecimal.valueOf((Integer) number); if (number instanceof BigInteger) return new BigDecimal((BigInteger) number); // BigDecimal.valueOf( double ) is equivalent to new BigDecimal( Double.toString( double ) ). // new BigDecimal( double ) is inaccurate due to floating point representation errors. if (number instanceof Double) return BigDecimal.valueOf((Double) number); // BigDecimal.valueOf( float ) doesn't exist (at the time of Java 8) // and produces call to BigDecimal.valueOf( double ). // It leads float to double conversion. // The value in float could be accurately converted to string (e.g. 1e23 to "1.0e23"). // But the same value in double has more precision places, so it is converted to string less accurately. // It sounds paradoxically, so let's take a look at the example: // 1E23 is 9.999999999999999E22 // 1E23F is 1.0 E23 // ( double )1E23F is 9.999999778196308E22 // The value has more precision places but is less accurate. // So it's better not to cast float to double but rather work with string representation of float // and call new BigDecimal( Float.toString( float ) ) by analogy to double. if (number instanceof Float) return new BigDecimal(Float.toString((Float) number)); if (number instanceof Short) return BigDecimal.valueOf((Short) number); if (number instanceof Byte) return BigDecimal.valueOf((Byte) number); if (number instanceof AtomicInteger) return BigDecimal.valueOf(((AtomicInteger) number).get()); if (number instanceof AtomicLong) return BigDecimal.valueOf(((AtomicLong) number).get()); return BigDecimal.valueOf(number.doubleValue()); } }