Java Number Format Pattern formatNumber(int num)

Here you can find the source of formatNumber(int num)

Description

format Number

License

MIT License

Parameter

Parameter Description
num the number to format.

Return

a nicely formatted string representation of the number.

Declaration

public static String formatNumber(int num) 

Method Source Code

//package com.java2s;
/** Copyright by Barry G. Becker, 2000-2011. Licensed under MIT License: http://www.opensource.org/licenses/MIT  */

import java.text.DecimalFormat;

public class Main {
    private static final DecimalFormat expFormat_ = new DecimalFormat("0.###E0");
    private static final DecimalFormat format_ = new DecimalFormat("###,###.##");
    private static final DecimalFormat intFormat_ = new DecimalFormat("#,###");

    /**//from   w  w  w.  j  av  a  2 s  .com
     * Show a reasonable number of significant digits.
     * @param num the number to format.
     * @return a nicely formatted string representation of the number.
     */
    public static String formatNumber(double num) {
        double absnum = Math.abs(num);

        if (absnum == 0) {
            return "0";
        }
        if (absnum > 10000000.0 || absnum < 0.000000001) {
            return expFormat_.format(num);
        }

        if (absnum > 1000.0) {
            format_.setMinimumFractionDigits(0);
            format_.setMaximumFractionDigits(0);
        } else if (absnum > 100.0) {
            format_.setMinimumFractionDigits(1);
            format_.setMaximumFractionDigits(1);
        } else if (absnum > 1.0) {
            format_.setMinimumFractionDigits(1);
            format_.setMaximumFractionDigits(3);
        } else if (absnum > 0.0001) {
            format_.setMinimumFractionDigits(2);
            format_.setMaximumFractionDigits(5);
        } else if (absnum > 0.000001) {
            format_.setMinimumFractionDigits(3);
            format_.setMaximumFractionDigits(8);
        } else {
            format_.setMinimumFractionDigits(6);
            format_.setMaximumFractionDigits(11);
        }

        return format_.format(num);
    }

    /**
     * @param num the number to format.
     * @return a nicely formatted string representation of the number.
     */
    public static String formatNumber(long num) {
        return intFormat_.format(num);
    }

    /**
     * @param num the number to format.
     * @return a nicely formatted string representation of the number.
     */
    public static String formatNumber(int num) {
        return intFormat_.format(num);
    }
}

Related

  1. formatInteger(Object obj)
  2. formatIntoCurr(String str_number, int digits)
  3. formatLong(long value)
  4. formatNumber(final long number)
  5. formatNumber(final long number)
  6. formatNumber(int source)
  7. formatNumber(long number)
  8. formatNumber(long number)
  9. formatNumber(Number num)