Is there a quick way of making a float always have two decimal points. Even if its double 0. Im trying to represent currency and just cant get it working properley.
Joined: Mar 22, 2005
I'm not sure what "two decimal points" means (maybe two fractional digits?), but check out the java.text.DecimalFormat class. It lets you format decimal numbers with as many leading and trailing digits as you like.
as long as you are aware of potential problems, you'll probably be fine. but remember that floats are not actual representations of the values you think they are. when you think you have 1.01, you really have something like 1.010000000000007. if you add enough together, bad things can happen.
Joined: Oct 13, 2005
If you just want to print with two decimal places, try something likeIt only works in J5.0, however.
And I agree with the people who imply you shouldn't use a float for money in the first place.
for integer arithmetic tryJust make sure your total amount can never exceed approx $20000000
Ouch. I have just noticed my mistake. For "System.printf" read "System.out.printf." CR [ May 25, 2006: Message edited by: Campbell Ritchie ]
Joined: Apr 27, 2006
I would use the BigDecimal class for currency, it takes care of all the floating point worries under the hood, and it allows you to perform mathematical functions.
Could try harder
Joined: Dec 12, 2005
Thank you for all your suggestions As the machine isnt actually using real money im just going to keep it as a float for now and use one of the simpler suggestions from above I had noticed that about the float was quite interesting but for the purposes of the machine its just a representation of a number
Plus gives me something to comment on in the report don't it
Joined: Jan 29, 2003
The Time and Money code library is a nifty example of the Domain Driven Design or Domain Specific Language style. See how Gregor Hohpe describes his experience with the package as an introduction. It really points out how much Calendar bites.
Note well the caveat - the package is very cool, but hasn't been proven in production.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Aug 03, 2004
Floating point numbers and not good for currency. Fixed point representation is much better. I would use int or long and store the amount in cents.