Scale BigDecimal object to prefer scale. - Java java.math

Java examples for java.math:BigDecimal

Description

Scale BigDecimal object to prefer scale.

Demo Code


//package com.java2s;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
    public static void main(String[] argv) throws Exception {
        BigDecimal value = new BigDecimal("1234");
        int scale = 2;
        System.out.println(scale(value, scale));
    }//from w w  w  .  j  a va  2s  . c o m

    /**
     * Scale BigDecimal object to prefer scale. If scale is different than scale of object scale to default scale
     *
     * @param value BigDecimal object
     * @param scale value of prefer scale
     *
     * @return BigDecimal object with applay scale
     */
    public static BigDecimal scale(BigDecimal value, int scale) {
        if (value != null && value.scale() != scale) {
            return value.setScale(scale, RoundingMode.HALF_UP);
        } else {
            return value;
        }
    }
}

Related Tutorials