12
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.

3 Answers 3

21
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.

Sign up to request clarification or add additional context in comments.

6 Comments

thanks I looked at the documentation, but could not really understand. I was confused, should'nt zero be taken in its literal meaning ?
As explained in the documentation, the zero should not be taken literal when used in a format string.
"There will be atleast 1 digit", do you want to say that if there was no digit before decimal that i if i pass .7, it will return me 0.70 after appending a leading zero ?
+1, but please don't link to the docs. for an obsolete JRE. URL adjusted.
Thanks Andrew. Hadn't noticed that.
|
5

# 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.

Comments

4

With the zero before the dp, small numbers like 0.23 will be displayed as 0.23. Without it you will not get the leading zero, so it is just displayed as .23. If you have a spreadsheet like excel you can check this there too.

6 Comments

I just tested this with ###.### and I get 0.23 which is quite annoying as I don't want the leading zero for what I'm doing
@MikeB - I just checked with Excel 2003 and the leading zero is definitely dropped if the cell formatting is ###.###
@DaveRiz but this is a java question
@MikeB - yes, I know that - but the same principle applies in excel. I'm a java programmer, I use excel as a tool to illustrate the point.
I believe java should be doing what Excel is doing but it appears to me that it's not. This test failed for me in java, : assertThat(new DecimalFormat("###.###").format(0.23d), is(".23"));
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.