Here you can find the source of coerce(BigDecimal val, int targetPrecision, int targetScale)
Parameter | Description |
---|---|
val | the BigDecimal value to coerce. |
targetPrecision | the target precision of the coerced value. |
targetScale | the target scale of the coerced value. |
public static BigDecimal coerce(BigDecimal val, int targetPrecision, int targetScale)
//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; } }