Java: Decimal Format to Easily Create Custom Output

Contributor Icon Contributed by William_Wilson Date Icon April 5, 2006  
Tag Icon Tagged: Java programming

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)

Previous recipe | Next recipe |
 
  • Iridium
    Thank you William, this was exceptionally helpful.
  • Zhen Dong
    helpful and concise. :) . nice job.
  • DK
    wow..that was so simple...and easy to undastand...
    thanks..
  • deta
    it's helpful. thank you
blog comments powered by Disqus