Java Locale Format formatToString(double num, int decPlaces)

Here you can find the source of formatToString(double num, int decPlaces)

Description

Returns the supplied number formatted as a string with the given number of decimal places fixed and padded with zeroes if needed.

License

Open Source License

Parameter

Parameter Description
num the number to format
decPlaces the number of places to display

Declaration

public static String formatToString(double num, int decPlaces) 

Method Source Code

//package com.java2s;
/*/*from  w  w  w .j a v a2s .c o m*/
 * Copyright 1998-2007 The Brookings Institution, NuTech Solutions,Inc., Metascape LLC, and contributors. 
 * All rights reserved.
 * This program and the accompanying materials are made available solely under the BSD license "ascape-license.txt".
 * Any referenced or included libraries carry licenses of their respective copyright holders. 
 */

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Main {
    /**
     * Returns the supplied number formatted as a string with the given number of decimal places fixed
     * and padded with zeroes if needed.
     * For example, <code>formatToString(23.436765, 2) would return "23.44".
     * @param num the number to format
     * @param decPlaces the number of places to display
     */
    public static String formatToString(double num, int decPlaces) {
        NumberFormat nf = NumberFormat.getNumberInstance();

        if (Math.abs(num) >= 1.0E9) {
            // generate scientific notation
            try { // we use "try" because the number format of some locales may not support scientific notation
                ((DecimalFormat) nf).applyPattern("0.###E0");
            } catch (Exception e) {
            }
        }

        nf.setGroupingUsed(false);
        nf.setMinimumFractionDigits(decPlaces);
        nf.setMaximumFractionDigits(decPlaces);

        return nf.format(num);
    }
}

Related

  1. formattedFromLong(long l, Locale locale)
  2. formattedToDouble(String str, Locale loc)
  3. formatTime(Calendar calendar, String format)
  4. formatTime(final double theTime)
  5. formatTo(StringBuilder buf, int[] d, String sep)
  6. formatValues(double x, double y)
  7. formatZahl(Number nZahl, int iNachkommastellen, Locale locale)