Java Double Number Format formatDouble(double value)

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

Description

This method takes double value as a parameter and formats it to two decimal points and returns the formatted value.

License

Open Source License

Parameter

Parameter Description
value value to be formatted

Return

double formattedvalue

Declaration

public static String formatDouble(double value) 

Method Source Code

//package com.java2s;
/*//from   ww  w  .ja  va  2 s .c  o m
 * @(#)ConversionUtil.java
 *
 * Copyright by ObjectFrontier, Inc.,
 * 12225 Broadleaf Lane, Alpharetta, GA 30005, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of ObjectFrontier, Inc. You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of
 * the license agreement you entered into with ObjectFrontier.
 */

public class Main {
    /**
     * This method takes double value as a parameter and formats it to
     * two decimal points and returns the formatted value.
     *
     * @param   value value to be formatted
     * @return  double formattedvalue
     */
    public static String formatDouble(double value) {

        double valueHundred = roundDouble(value) * 100;
        Double temp = new Double(roundDouble(valueHundred));
        String cost = String.valueOf(temp.longValue());

        if (cost.equals("0")) {
            cost = "0.00";
        } else {
            cost = cost.substring(0, cost.length() - 2) + "." + cost.substring(cost.length() - 2);
        }

        return cost;
    }

    /**
     * This method takes double value as a parameter and rounds it to
     * two decimal points and returns the rounded value.
     *
     * @param   value value to be rounded
     * @return  double roundedvalue
     */
    public static double roundDouble(double value) {

        int decimalPlace = 2;
        double power_of_ten = 1;

        while (decimalPlace-- > 0) {
            power_of_ten *= 10.0;
        }

        return Math.round(value * power_of_ten) / power_of_ten;
    }
}

Related

  1. formatDouble(double v, int decimalPlaces)
  2. formatDouble(double val)
  3. formatDouble(double val)
  4. formatDouble(double val, int prec)
  5. formatDouble(double val, int precision)
  6. formatDouble(double value)
  7. formatDouble(double value)
  8. formatDouble(double value)
  9. formatDouble(double value, int decimals)