Java Number Format formatNumber(double dd)

Here you can find the source of formatNumber(double dd)

Description

Write the number in bbbb.bb format needed for currency.

License

Open Source License

Parameter

Parameter Description
dd the input double number

Declaration

public final static String formatNumber(double dd) 

Method Source Code

//package com.java2s;
/**//from w w w . j ava  2 s .  c  o  m
 * @copyright Copyright (C) 2014-2016 City of Bloomington, Indiana. All rights reserved.
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
 * @author W. Sibo <sibow@bloomington.in.gov>
 *
 */

public class Main {
    /**
     * Write the number in bbbb.bb format needed for currency.
     * = toFixed(2)
     * @param dd the input double number
     * @returns the formated number as string
     */
    public final static String formatNumber(double dd) {
        //
        String str = "" + dd;
        String ret = "";
        int l = str.length();
        int i = str.indexOf('.');
        int r = i + 3; // required length to keep only two decimal
        // System.err.println(str+" "+l+" "+r);
        if (i > -1 && r < l) {
            ret = str.substring(0, r);
        } else {
            ret = str;
        }
        return ret;
    }

    final static String formatNumber(String that) {

        int ind = that.indexOf(".");
        int len = that.length();
        String str = "";
        if (ind == -1) { // whole integer
            str = that + ".00";
        } else if (len - ind == 2) { // one decimal
            str = that + "0";
        } else if (len - ind > 3) { // more than two
            str = that.substring(0, ind + 3);
        } else
            str = that;

        return str;
    }
}

Related

  1. FormatIntNoWithZero(int pNumber, int tolLen)
  2. formatLineNumber(String lineNumber)
  3. formatMs(long number)
  4. formatNationalNumber(String nationalNumber)
  5. formatNCPDPNumber(String origNumber, int decimalPoints)
  6. formatNumber(double dscore)
  7. formatNumber(double number, int decimalPlaces)
  8. formatNumber(Double val, int numDec, int width)
  9. formatNumber(double value)