Here you can find the source of toBigDecimal(Number n)
Parameter | Description |
---|---|
n | The number |
public static BigDecimal toBigDecimal(Number n)
//package com.java2s; /******************************************************************************* * Copyright 2009, 2010 Innovation Gate GmbH * /* ww w. j a v a2 s . com*/ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ import java.math.BigDecimal; import java.math.BigInteger; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; public class Main { /** * Converts any number to a BigDecimal, suited for comparison and (monetary) arithmetic. * This class uses conversions that avoid rounding errors by forced conversion for the * Number types from JRE. Fallback for other types is to convert them to Double. * @param n The number */ public static BigDecimal toBigDecimal(Number n) { if (n instanceof BigDecimal) { return (BigDecimal) n; } if (n instanceof Long) { return new BigDecimal((Long) n); } else if (n instanceof Integer) { return new BigDecimal((Integer) n); } else if (n instanceof Float) { return new BigDecimal((Float) n); } else if (n instanceof Double) { return new BigDecimal((Double) n); } else if (n instanceof Short) { return new BigDecimal((Short) n); } else if (n instanceof Byte) { return new BigDecimal((Byte) n); } else if (n instanceof BigInteger) { return new BigDecimal((BigInteger) n); } else if (n instanceof AtomicInteger) { return new BigDecimal(n.intValue()); } else if (n instanceof AtomicLong) { return new BigDecimal(n.longValue()); } else { return new BigDecimal(n.doubleValue()); } } }