Thought and Freedom

Articles for those who think. By Terry Pearson

Display a Double with two decimal places in Java

with 2 comments

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.

Related posts:

  1. Installing a Java Compiler So you have a great looking program. Perhaps you typed out the source code for the hello world tutorial. Now, you need to transfer that source code into a computer...
  2. Java SE 6 Released. Sun Microsystems announced that they just released Java SE 6. Depending on who you ask, this is a great thing, or just so so....
  3. Java: Hello World Java is becoming an important language for every programmer to know. It is key to creating platform independent software. In my opinion, Java will continue to play a greater role...
  4. The most important reference document for Java If you are new to Java, or are more experienced than anyone, you still need to look up stuff. Every developer has moments in their language of choice where they...
  5. Learn Java Swing If you talk to a lot of programmers these days, you will hear an increased number of conversations about Java. With the open sourcing of parts of the actual language,...

Written by Terry Pearson

January 28th, 2007 at 1:48 am

2 Responses to 'Display a Double with two decimal places in Java'

Subscribe to comments with RSS or TrackBack to 'Display a Double with two decimal places in Java'.

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

    Like or Dislike: Thumb up 2 Thumb down 0

    burnmind

    23 Sep 09 at 16:50

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

    Like or Dislike: Thumb up 0 Thumb down 0

    Jeanna

    4 Dec 09 at 18:51

Leave a Reply


Creative Commons License
Terry Pearson - The Blog by Terry Pearson
is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.