• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

setting precision for float values

 
kumaraswamy adurthi
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in java if i want to print a float value of 125.00 it will print 125.0 only how can i print 125.00 using java .
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, you create an instance of the DecimalFormat class (in java.text), passing the appropriate String pattern to the constructor. Then you call the format method on that instance, passing the value you want formatted.

For details, see the API for DecimalFormat.

Note that this is only formatting a String representation of the value. You are not changing any numerical "precision."

[ September 27, 2005: Message edited by: marc weber ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're using Java 1.5, you can use the new printf method in PrintStream (e.g., System.out).

Note the "printf" method, which is taking a floating-point specifier (%f) as an argument along with the float value. Here, the specifier "%3.2f" indicates a number at least 3 characters wide with 2 decimal places.

For details on the specifier, see Formatter.
[ September 27, 2005: Message edited by: marc weber ]
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I create a String that represents a double (or float) value with only 2 decimal places?

http://jqa.tmorris.net/faq/GetQAndA.action?qids=46&showAnswers=true
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two decimal points makes me think of money. Ok, I drive by the PowerBall billboard on the way to work and think of money most of the morning. Anyhow, using floating point math for money will likely make you unhappy in the long run. Floats are good for very large numbers, like the number of atoms in the sun, but not for precise arithmetic like a checking account. Let us know if you're doing money and we'll throw out some alternative ideas.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stan James:
... Let us know if you're doing money and we'll throw out some alternative ideas.

Excellent point. Primitive floating-points are (arguably) good for homework assignments, but not real money.

(I'm scheduled to win the PowerBall jackpot tonight. When I receive my winnings, I'll let you know if I observe any lack-of-precision errors.)
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic