I’m working on a Java/Groovy program. I have a double variable that holds a number that was typed in by a user. What I really want to know is how many numbers the user typed to the right of the decimal place. Something like:
double num = 3.14
num.getPlaces() == 2
Of course, you can’t do this with a double since that’s using IEEE floating points and it’s all an approximation.
Assuming that I can’t get at the string the user typed, but only have access to the double the value has been stored in, is there a way I can scrub that double though a BigDecimal or somesuch to get the “real” number of decimal places? (When the double gets displayed on the screen, it gets it right, so I assume there is a way to at least guess well?)
No, you can’t… because there are lots of different strings the user could have typed in which would all be parsed to the same value.
The “real” number is almost certain to have more decimal places than the user typed. For example, 3.14 is stored as exactly 3.140000000000000124344978758017532527446746826171875. I don’t think you want to display that to the user.
To make the problem clearer, you can’t tell from the double value whether the user actually entered:
Those four strings will all give you the same value – which should make it obvious that you can’t possibly get back to what the user typed in.
If at all possible, change the parsing code and use
BigDecimalthroughout.