Java Decimal Round round(double d, int n)

Here you can find the source of round(double d, int n)

Description

round

License

Apache License

Declaration

public static String round(double d, int n) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.math.BigDecimal;

import java.text.DecimalFormat;

public class Main {
    public static String round(double d, int n) {
        if (d == 0) {
            d = 0;//  ww w .ja va 2 s. co m
        }
        if (n < 0) {
            n = 0;
        }
        String str = "";
        if (n == 0) {
            str = "0";
        } else {
            str = "0.";
        }
        for (int i = 0; i < n; i++) {
            str = str + "0";
        }
        DecimalFormat formater = new DecimalFormat(str);
        BigDecimal b = new BigDecimal(d + "");
        double tempd = b.setScale(n, BigDecimal.ROUND_HALF_UP)
                .doubleValue();

        if (tempd == 0) {
            tempd = 0;
        }
        return formater.format(tempd);
    }
}

Related

  1. getRoundedValue(double doubleValue)
  2. getRoundedValue(double value)
  3. round(double d, int p)
  4. round(double dValue)
  5. round(double number)
  6. round(double unrounded, int precision)