Java Number Format formatNumber(double number, int decimalPlaces)

Here you can find the source of formatNumber(double number, int decimalPlaces)

Description

Format the given number as a String, including the given number of decimal places.

License

Open Source License

Parameter

Parameter Description
number the number to format
decimalPlaces the number of decimal places to include

Return

the formatted String

Declaration

public static String formatNumber(double number, int decimalPlaces) 

Method Source Code

//package com.java2s;
/*//from  ww  w.  j  a  v a 2 s .c o m
 * #%L
 * Cytoscape Work Swing Impl (work-swing-impl)
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2006 - 2013 The Cytoscape Consortium
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 2.1 of the 
 * License, or (at your option) 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 Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-2.1.html>.
 * #L%
 */

public class Main {
    /**
     * Format the given number as a String, including the given number of
     * decimal places.
     * @param number the number to format
     * @param decimalPlaces the number of decimal places to include
     * @return the formatted String
     */
    public static String formatNumber(double number, int decimalPlaces) {
        String s = String.valueOf(number);
        int idx1 = s.indexOf('.');
        if (idx1 == -1) {
            return s;
        } else {
            int idx2 = s.indexOf('E');
            int dp = decimalPlaces + (idx2 >= 0 ? 0 : 1);
            String t = s.substring(0, Math.min(idx1 + dp, s.length()));
            if (idx2 >= 0)
                t += s.substring(idx2);
            return t;
        }
    }
}

Related

  1. formatMs(long number)
  2. formatNationalNumber(String nationalNumber)
  3. formatNCPDPNumber(String origNumber, int decimalPoints)
  4. formatNumber(double dd)
  5. formatNumber(double dscore)
  6. formatNumber(Double val, int numDec, int width)
  7. formatNumber(double value)
  8. formatNumber(double value)
  9. formatNumber(final long number)