Java Fraction Format formatNumber(double num)

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

Description

Show a reasonable number of significant digits.

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(double 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 .  ja  va 2 s . c  o m
     * 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. formatNum(double d)
  2. formatNum(double num, int numfracdigits)
  3. formatNum(float value)
  4. formatNumber(double decimal)
  5. formatNumber(double i)
  6. formatNumber(double num)
  7. formatNumber(double number)
  8. formatNumber(double number)
  9. formatNumber(double number, int decimal)