Java BigDecimal Calculate coerce(BigDecimal val, int targetPrecision, int targetScale)

Here you can find the source of coerce(BigDecimal val, int targetPrecision, int targetScale)

Description

Attempts to coerce a big decimal to a target precision and scale and returns the result.

License

Apache License

Parameter

Parameter Description
val the BigDecimal value to coerce.
targetPrecision the target precision of the coerced value.
targetScale the target scale of the coerced value.

Return

the coerced BigDecimal value.

Declaration

public static BigDecimal coerce(BigDecimal val, int targetPrecision, int targetScale) 

Method Source Code


//package com.java2s;
// Licensed to the Apache Software Foundation (ASF) under one

import java.math.BigDecimal;

import java.math.RoundingMode;

public class Main {
    /**//from w  w  w.  ja v a2s .  co  m
     * Attempts to coerce a big decimal to a target precision and scale and
     * returns the result. Throws an {@link IllegalArgumentException} if the value
     * can't be coerced without rounding or exceeding the targetPrecision.
     *
     * @param val the BigDecimal value to coerce.
     * @param targetPrecision the target precision of the coerced value.
     * @param targetScale the target scale of the coerced value.
     * @return the coerced BigDecimal value.
     */
    public static BigDecimal coerce(BigDecimal val, int targetPrecision, int targetScale) {
        if (val.scale() != targetScale) {
            try {
                val = val.setScale(targetScale, RoundingMode.UNNECESSARY);
            } catch (ArithmeticException ex) {
                throw new IllegalArgumentException(
                        "Value scale " + val.scale() + " can't be coerced to target scale " + targetScale + ". ");
            }
        }
        if (val.precision() > targetPrecision) {
            throw new IllegalArgumentException("Value precision " + val.precision()
                    + " (after scale coercion) can't be coerced to target precision " + targetPrecision + ". ");
        }
        return val;
    }
}

Related

  1. calculateMonthCapital(BigDecimal eachIssueMoney, BigDecimal eachMonthInterest)
  2. calculateMonthInterest(Float interestRate, BigDecimal investmoney)
  3. calculatePercentChange(BigDecimal from, BigDecimal to)
  4. calculateProfit(BigDecimal totalAmt, Integer duration, BigDecimal rate)
  5. calculateRatioInDecimal(BigDecimal numberA, BigDecimal numberB)
  6. cosh(final BigDecimal dec, final int scale, final RoundingMode mode)
  7. cosine(BigDecimal x)