Java Double Number Format formatDouble(double d, int precision)

Here you can find the source of formatDouble(double d, int precision)

Description

Returns a string of the double with the specified floating point precision with zeroes added if required to achieve the precision.
double 10.03 with precision 4 will result in 10.0300
double 2.123456 with precision 4 will result in 2.1234

License

Open Source License

Parameter

Parameter Description
d a parameter
precision a parameter

Declaration

public static String formatDouble(double d, int precision) 

Method Source Code

//package com.java2s;
/**/* w  w w .ja  va2  s . c  o m*/
 * Stringter: Workbench for string editing
 *
 * Copyright (C) 2015 Zdravko Petkov
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Returns a string of the double with the specified floating point precision
     * with zeroes added if required to achieve the precision.<br>
     *
     * <code>double 10.03 with precision 4 will result in 10.0300</code><br>
     * <code>double 2.123456 with precision 4 will result in 2.1234</code><br>
     *
     * @param d
     * @param precision
     * @return
     */
    public static String formatDouble(double d, int precision) {
        String result = String.valueOf(d);
        int floatingPoint = result.indexOf('.');
        int addZeroes = -(result.length() - (floatingPoint + 1) - precision);
        if (addZeroes < 0) {
            return result.substring(0, floatingPoint + 1 + precision);
        } else {
            for (int i = 0; i < addZeroes; i++) {
                result = result + "0";
            }
            return result;
        }
    }
}

Related

  1. formatDouble(double d)
  2. formatDouble(double d)
  3. formatDouble(double d, int n)
  4. formatDouble(double d, int n)
  5. formatDouble(double d, int n, String pad)
  6. formatDouble(double inDouble, boolean inComma, int inCommaPos)
  7. formatDouble(double num, int width, int precision)
  8. FormatDouble(double p_value, int p_numberOfDecimalPlaces)
  9. formatDouble(double source, int decimals, int precision)