Is there any way to get the number of digits after the decimal point in Java double?
I am developing a Java / groovy program I have a double variable that contains a number entered by the user What I really want to know is how many numbers the user typed to the right of the decimal point It's like:
double num = 3.14 num.getPlaces() == 2
Of course, you can't do this with double because it uses IEEE floating point numbers and it's all approximate
Suppose I can't get the string typed by the user, but can only access the double of the stored value. Is there any way to erase the double through BigDecimal, or something can get the "real" decimal places? (when double is displayed on the screen, it will be correct, so I think there is a way to at least guess?)
Solution
No, you can't... Because users can enter many different strings, and all strings will be parsed to the same value
The "real" number is almost certainly smaller than the number entered by the user For example, 3.14 is stored as 3.140000000000000124344978758017532527446826171875 I don't think you want to show it to users
To make the problem clearer, you cannot tell the user from the double value whether it actually entered:
3.14 3.140 3.140000 3.14000000000000012434
All four strings will give you the same value - it should be obvious that you can't go back to what the user typed
If possible, change the parsing code and always use BigDecimal