round double in scale - Java java.lang

Java examples for java.lang:double

Description

round double in scale

Demo Code


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

public class Main {

    private static final int DEFAULT_DIV_SCALE = 10;

    public static double round(double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }// w  w w. j av  a2  s. c  o  m
        if (isInvalidDouble(v)) {
            return v;
        }
        BigDecimal b = createBigDecimal(v);
        return b.divide(BigDecimal.ONE, scale, BigDecimal.ROUND_HALF_UP)
                .doubleValue();
    }

    public static boolean isInvalidDouble(double v) {
        return Double.isInfinite(v) || Double.isNaN(v);
    }

    public static BigDecimal createBigDecimal(double v) {
        return new BigDecimal(v);
    }

    public static BigDecimal createBigDecimal(String strVal) {
        if (strVal == null || strVal.equals("")) {
            return new BigDecimal(0);
        }
        return new BigDecimal(strVal);
    }

    public static BigDecimal createBigDecimal(float f) {
        return new BigDecimal(f);
    }

    public static double divide(double v1, double v2) {
        return divide(v1, v2, DEFAULT_DIV_SCALE);
    }

    public static double divide(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = createBigDecimal(v1);
        BigDecimal b2 = createBigDecimal(v2);
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}

Related Tutorials