Java Double Number Format formatDoubleForDecimalPlaces(double d, int decimalcount)

Here you can find the source of formatDoubleForDecimalPlaces(double d, int decimalcount)

Description

Utility function to format a given double to the accuracy of decimalcount decimal places.

License

Open Source License

Parameter

Parameter Description
d The double to be formatted.
decimalcount The amount of post period decimal places.

Return

The formatted double as a String.

Declaration

public static String formatDoubleForDecimalPlaces(double d, int decimalcount) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015 Joakim von Kistowski
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

public class Main {
    /**//from  ww  w.j  a v  a  2  s . c o  m
     * Utility function to format a given double to the accuracy of decimalcount decimal places.
     * @param d The double to be formatted.
     * @param decimalcount The amount of post period decimal places.
     * @return The formatted double as a String.
     */
    public static String formatDoubleForDecimalPlaces(double d, int decimalcount) {
        long intpredecimals = (long) d;
        double tenexp = Math.pow(10, decimalcount);
        double decimals = d - intpredecimals;
        double postdecimals = decimals * (long) tenexp;
        long intpostdecimals = (long) postdecimals;
        //round
        if ((postdecimals - intpostdecimals) >= 0.5) {
            intpostdecimals++;
        }
        return intpredecimals + "." + intpostdecimals;
    }
}

Related

  1. formatDouble(final double value)
  2. formatDouble(final Object value)
  3. formatDouble(String value)
  4. formatDoubleAsString(double num, int n)
  5. formatDoubleFast(double source, int decimals, int precision, StringBuffer target)
  6. formatDoubleInfinity(Double d)
  7. formatDoublePrecise(double source, int decimals, int precision, StringBuffer target)
  8. formatDoubleToFixedLength(String value, int length)
  9. formatDoubleToString(double d)