Java Decimal Round getRoundedValue(double value)

Here you can find the source of getRoundedValue(double value)

Description

Get rounded double value, according to the value of the double.

License

Apache License

Parameter

Parameter Description
value a parameter

Declaration

public static String getRoundedValue(double value) 

Method Source Code

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

import java.text.DecimalFormat;

public class Main {
    private static final String TWO_DECIMALS_FORMAT = "##.##";
    private static final String MAX_DECIMALS_FORMAT = "##.#####";
    private static final String DECIMALS_FORMAT_TOKEN = "#";

    /**/*from   w w w  . j a v a 2 s . c om*/
     * Get rounded double value, according to the value of the double.
     * Max rounding will be upto 4 decimals
     * For values gte 0.1, use ##.## (eg. 123, 2.5, 1.26, 0.5, 0.162)
     * For values lt 0.1 and gte 0.01, use ##.### (eg. 0.08, 0.071, 0.0123)
     * For values lt 0.01 and gte 0.001, use ##.#### (eg. 0.001, 0.00367)
     * This function ensures we don't prematurely round off double values to a fixed format, and make it 0.00 or lose out information
     * @param value
     * @return
     */
    public static String getRoundedValue(double value) {
        StringBuffer decimalFormatBuffer = new StringBuffer(
                TWO_DECIMALS_FORMAT);
        double compareValue = 0.1;
        while (value > 0
                && value < compareValue
                && !decimalFormatBuffer.toString().equals(
                        MAX_DECIMALS_FORMAT)) {
            decimalFormatBuffer.append(DECIMALS_FORMAT_TOKEN);
            compareValue = compareValue * 0.1;
        }
        DecimalFormat decimalFormat = new DecimalFormat(
                decimalFormatBuffer.toString());
        return decimalFormat.format(value);
    }
}

Related

  1. getRoundedValue(double doubleValue)
  2. round(double d, int n)
  3. round(double d, int p)
  4. round(double dValue)
  5. round(double number)