Java examples for java.lang:double
round double value by scale
//package com.java2s; import java.math.BigDecimal; public class Main { public static void main(String[] argv) throws Exception { double val = 2.45678; int scale = 2; System.out.println(round(val, scale)); }//from w w w. ja v a 2 s.c o m private static final int DEF_DIV_SCALE = 10; public static double round(double val, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(val)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static double divide(double dividend, double divisor) { return divide(dividend, divisor, DEF_DIV_SCALE); } public static double divide(double dividend, double divisor, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(Double.toString(dividend)); BigDecimal b2 = new BigDecimal(Double.toString(divisor)); return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } }