Java BigDecimal from toBigDecimal(Number number, int scale)

Here you can find the source of toBigDecimal(Number number, int scale)

Description

to Big Decimal

License

Apache License

Declaration

public static BigDecimal toBigDecimal(Number number, int scale) 

Method Source Code


//package com.java2s;
/*//from w ww .j av a 2s  . co m
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to you 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;

public class Main {
    public static BigDecimal toBigDecimal(Number number, int scale) {
        BigDecimal bd = toBigDecimal(number);
        return rescaleBigDecimal(bd, scale);
    }

    public static BigDecimal toBigDecimal(Number number) {
        if (number == null) {
            return null;
        }
        if (number instanceof BigDecimal) {
            return (BigDecimal) number;
        } else if ((number instanceof Double) || (number instanceof Float)) {
            // For JDK 1.4 compatibility
            return new BigDecimal(number.doubleValue());
            //return BigDecimal.valueOf(((Number) number).doubleValue());
        } else if (number instanceof BigInteger) {
            return new BigDecimal((BigInteger) number);
        } else {
            return new BigDecimal(number.longValue());
        }
    }

    public static BigDecimal rescaleBigDecimal(BigDecimal bd, int scale) {
        if (bd != null) {
            bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        return bd;
    }
}

Related

  1. toBigDecimal(Number num)
  2. toBigDecimal(Number number)
  3. toBigDecimal(Number number)
  4. toBigDecimal(Number number)
  5. toBigDecimal(Number number)
  6. toBigDecimal(Number price)
  7. toBigDecimal(Object n)
  8. toBigDecimal(Object obj)
  9. toBigDecimal(Object obj)