Java Fraction Format formatNumber(String number, int maxFractionalDigits)

Here you can find the source of formatNumber(String number, int maxFractionalDigits)

Description

Formats the provided number with the specified number of fractional digits If number arg is not a number, returns the String

License

Open Source License

Declaration

public static String formatNumber(String number, int maxFractionalDigits) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.text.NumberFormat;

public class Main {
    /**//from w ww  . j  ava  2s.co  m
     * Formats the provided number with the specified number of fractional digits
     * If number arg is not a number, returns the String
     */
    public static String formatNumber(String number, int maxFractionalDigits) {

        try {
            NumberFormat nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(maxFractionalDigits);
            return nf.format(Double.parseDouble(number));
        } catch (Exception ex) {
            return number;
        }
    }

    public static String formatNumber(double number, int maxFractionalDigits) {
        try {
            NumberFormat nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(maxFractionalDigits);
            return nf.format(number);
        } catch (Exception ex) {
            return String.valueOf(number);
        }
    }
}

Related

  1. formatNumber(Float d, int scalar)
  2. formatNumber(float num, String format)
  3. formatNumber(int fractionDigits, double value)
  4. formatNumber(String Format, double Num)
  5. formatNumber(String format, double number)
  6. formatNumberAttribute(double v)
  7. formatNumFraction(float num, int unit)
  8. formatNumValueWithComma(double val)
  9. formatoDecimal(String tipo, double valor)