• Post Reply Bookmark Topic Watch Topic
  • New Topic

Decimal Places  RSS feed

 
Shae Weathers
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I hope someone can lead me in the right direction. I am trying to format my currency to two decimal places, for instance, whenever I enter an amount like 75.50 is shows up as 75.5. Also whenever the program computes the change is comes out as 3.0900000034. Here is an example of the output I get

Enter amount of purchase:
98.00
Enter amount tendered:
101.09
You owe $98.0 and you gave me $101.09 your change amount is $3.0900000000000034.
Your change is:
3 dollars
0 quarters
0 dimes
1 nickels
4 pennies
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please just copy and paste the text from the console window, instead of attaching it as an image. It's easier to read (and to search on!) when you just copy and paste it as text. If you don't know how to copy text from the console, see this: How To: Copy To the Clipboard From the Windows Command Prompt.

To answer your question: You're most likely using float or double variables in your program to store the amounts of money. Those data types are not infinitely precise: you can get rounding errors when you perform computations with them.

To print a float or double with a specific number of decimal places, you can use class java.text.DecimalFormat, or use System.out.printf(), for example:

Note, however, that because of rounding errors you might see that the amount is one cent too low or too high. In "real" programs, you should never use floating-point data types for amounts of money: it's better to use an integer and store the amount in cents, or use BigDecimal (which can store numbers with arbitrary precision).
 
Shae Weathers
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have edited the original post to make it easier to read, thanks for the suggestion.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!