Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DecimalFormat pattern

public static String formatAmountUpToTwoDecimalNumber(String amount)
    {       
        if(amount==null || "".equals(amount))
        {
             return "";
        }  
        Double doubleAmount = Double.valueOf(amount);
        double myAmount = doubleAmount.doubleValue();
        NumberFormat f = new DecimalFormat("###,###,###,###,##0.00");
        String s = f.format(myAmount);
        return s;
    }

"###,###,###,###,##0.00", What exactly is the purpose of this pattern ? I believe it serves two purposes

  1. to group numbers, that is put thousand seperator comma
  2. to append two zeros after decimal if decimal is missing that is convert 23 to 23.00

But why there is "0" instead of "#" before decimal? what exactly is the purpose of this zero? Thanks for the help.

like image 698
Zohaib Avatar asked Dec 14 '11 10:12

Zohaib


People also ask

How do you write DecimalFormat in Java?

DecimalFormat myFormatter = new DecimalFormat(pattern); String output = myFormatter. format(value); System. out. println(value + " " + pattern + " " + output);

What does DecimalFormat return?

DecimalFormat toPattern() method in Java Return Value: This method returns a string which represents the pattern which is used to format the current state of this DecimalFormat instance.

Is Java DecimalFormat thread safe?

DecimalFormat isn't thread-safe, thus we should pay special attention when sharing the same instance between threads.


2 Answers

Symbol  Location    Localized?  Meaning
0       Number      Yes         Digit
#       Number      Yes         Digit, zero shows as absent 

From: http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

So # is not shown when there is no number. The leading 0 means there will be at least 1 digit before the decimal separator.

like image 84
Pieter Avatar answered Oct 12 '22 23:10

Pieter


# will put a digit only if it is not a leading zero. 0 will put a digit even if it is a trailing zero. You could use zeros in front, too, if you wanted a fixed number of digits printed.

like image 20
Sergey Kalinichenko Avatar answered Oct 13 '22 01:10

Sergey Kalinichenko