Java: Decimal Format to Easily Create Custom Output
The Decimal Format class is a poorly explained class in the java Documentation so i will clear up a little of it with an example.
you first need to import the DecimalFormat class:
import java.text.DecimalFormat;
then create a format object. this object can be used with doubles, as it uses a decimal. It uses a template String to teach Java how to ouput the objects.
*This example will be used as a standard format of money:
DecimalFormat money = new DecimalFormat("$0.00");
Now that you have a money object. (declared either globally or locally) you can now format your objects
*Note this example uses only 2 decimal places and a $, but any symbols or length is available.
As an example of prniting a double value:
double amount = 4.333333333;
System.out.println(money.format(amount));
what will be printed is: $4.33 as described by the template, this handles your percision and dollar sign with a single template!
Questions/Comments: william_a_wilson@hotmail.com
-William. ยง (marvin_gohan)










Iridium said on January 29, 2009
Thank you William, this was exceptionally helpful.
Zhen Dong said on March 6, 2009
helpful and concise. :) . nice job.
DK said on May 2, 2009
wow..that was so simple…and easy to undastand…
thanks..
deta said on July 13, 2009
it’s helpful. thank you
Anonymous said on September 2, 2010
#java #programming number-formatting made simple
Nvehmann said on September 17, 2010
Made Java formula precise….thank you
PeterWadethespider said on September 23, 2010
Thanks guy. you made my highschool comp sci easier
Kainthalwayswin said on September 29, 2010
Thank you very much…it help me a lot
t4thilina said on November 20, 2010
how to use that DecimalFormat in a static method ?
Piranha Urs said on January 19, 2011
Hi, this example works in Windows environment, but when we deploy in the unix environment, we doesn’t get $ symbol … can anyone explain me …
YSReddy said on January 28, 2011
Hi
DecimalFormat formatter = new DecimalFormat(“#,##,##,##0.00″);
double num = 1212245.67;
System.out.println(formatter.format(num));
The above code is showing as 1,212,245.67, but it should be 12,12,245.67
Anybody please help me with correct code.
Boyu_y said on May 27, 2011
The first comma to decimal point is 3 digits, so 1,212,245.67 is the correct result, if you change the pattern to #,##,##,##.00, the output should be 1,21,22,45.67. The number is always divided in equal size.
will pham said on October 20, 2011
how do i print 1, 2, 3, ……, 8, 9. as 01, 02, 03, ……, 08, 09
i have an array of size 10. myArray[10]
so far i have
for(int i = 0; i
Matt said on November 18, 2011
Awesome! Thanks for making this so clear. The other examples I found online confused the issue with a lot of unnecessary code. Simple is better for a Java noob like me.