• Post Reply Bookmark Topic Watch Topic
  • New Topic

enum - format 2 decimal currency  RSS feed

 
Anthony Stillwell
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Working on homework.
The question is:
Extra Credit: Correct the price format so that it displays a 2 decimal currency. (i.e. $1.40 is not written to the screen as $1.4)

I got everything to work but figuring out this 2 decimal currency. I know it is for extra credit but it is bugging me that I can not figure it out. I have tried several things like making the float into integer but compiler says not allowed in enum.

Would appreciate any suggestions or direction. Thanks in advance.

 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use String.format(), System.out.printf(), or java.text.DecimalFormat.

Or write your own routine that looks at the number or the String and adds a '0' to the end of the String where appropriate.
 
Anthony Stillwell
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jeff - I ended up writing a System.out.printf() and got it to work.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A good choice. But why are you using floats? They should be reserved for situations where you know you are dealing with a restricted range of values and you tolerate imprecision. For example, look at this Color constructor. You can use floats there because you are dealing with 256 different values in the range 0f-1.0f inclusive and the restricted precision (about 7 sig fig) isn’t important. you should really use BigDecimals. (Note that post is incomplete about number of figures after the decimal point.)By the way, when you use the code tags, put the code after the first ] and before the second [.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!