RSS:
Publications
Comments

Display a Double with two decimal places in Java

I just spent the longest time trying to find the easiest way to make a double display two decimal places in Java.

Basically, I wanted to output money information, and it would look better if the money data says “$5.00″ instead of “$5.0″ as is sometimes the case. There are so many “solutions” to this, that it is difficult to wade through them all.
The best solution I encountered was relatively easy. You can find it in Sun’s Java forums.

import java.text.DecimalFormat;

double d = 8.9909879;

DecimalFormat dFormat = new DecimalFormat(0.00″);

String formattedString = dFormat.format(d));

The above code will format a string that has two decimal point precision. It will give the number 8.99 instead of 8.9909879.

2 Comments to "Display a Double with two decimal places in Java"

  1. September 23, 2009 - 4:50 pm | Permalink

    Thanks for the solution. You’re missing a quote before “0.00″

  2. Jeanna's Gravatar Jeanna
    December 4, 2009 - 6:51 pm | Permalink

    I HEART YOU!! You just saved me so much time. Thanks!! :)

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <div align="" class="" dir="" id="" lang="" style="" xml:lang=""> <embed style="" type="" id="" height="" width="" src="" object=""> <iframe width="" height="" frameborder="" scrolling="" marginheight="" marginwidth="" src=""> <img alt="" align="" border="" class="" height="" hspace="" longdesc="" vspace="" src="" style="" width="" title="" usemap=""> <map name="" id=""> <object style="" height="" width="" param="" embed=""> <param name="" value=""> <pre style="" name="" class="" lang="" width="">