Tyson Lindner wrote:I'm writing a program that does some simple math problems on user inputted dollar amounts. I'm currently using double for those amounts.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Tyson Lindner wrote:The user input will still be double, is there a way to check how specific the input is? That way if the user puts in "125" I can have one print format, if its "125.75" I can have another, and if its "125.12352" I can print an error message.
Pat Farrell wrote:
Tyson Lindner wrote:The user input will still be double, is there a way to check how specific the input is? That way if the user puts in "125" I can have one print format, if its "125.75" I can have another, and if its "125.12352" I can print an error message.
No! The user input is not double. The user input is a String. its a String that may have look like: "125.12" or "125.12352"
It is never a double. The user input may also look like "12S.L2" where there is an S and a L instead of the proper digits 5 and 1 (one). It can look like "125.12 125.12"
You have to process/parse the user's input, see if it makes sense, and use it or give an error message.
Tyson Lindner wrote:Yeah I was parsing the string using Double.parseDouble() and catching a NumberFormatException, but 12.24523 is bad input for my purposes but won't throw an exception, so I'm wondering how I catch that.
Jeff Verdegan wrote:
Pat Farrell wrote:Never use float or double for money.
I don't think that will work. I don't think you can use the formatting tools in the core API to add decimal points to integers. You'd have to roll your own, I believe.
Tyson Lindner wrote:
Jeff Verdegan wrote:
Pat Farrell wrote:Never use float or double for money.
I don't think that will work. I don't think you can use the formatting tools in the core API to add decimal points to integers. You'd have to roll your own, I believe.
Yeah I'm currently trying to figure this out. I can convert the double to int,
but now I'm having trouble finding a way to print the integer back out with decimal places (if needed) in a JLabel.
I suppose I can convert back to double
Tyson Lindner wrote:Yeah I'm currently trying to figure this out. I can convert the double to int, but now I'm having trouble finding a way to print the integer back out with decimal places (if needed) in a JLabel. I suppose I can convert back to double and figure out how formatting works for JLabel which is something I was going to have to do anyway.
Pat Farrell wrote:
The standard approach is to use the Pattern and Matcher classes to process a regular expression. This also allows you to accept and ignore commas in the number. Sadly, its a bit complex to get the regex exactly right, you can get it close with a few minutes of effort, but getting it exact for all cases is a lot of effort.
Don't get me started about those stupid light bulbs. |