Reputation: 247
I'm a little bit confused because I lose precision all the time.
Maybe I'm operating with the wrong type. I have a String like "100.00". But when I do
Double.parseDouble("100.00") it is being cut off to 100. Need help. Thanks in advance.
Upvotes: 0
Views: 230
Reputation: 6414
Just use BigDecimal instead of Double like this:
BigDecimal houndred = new BigDecimal("100.00").setScale(2, BigDecimal.ROUND_HALF_UP);
BigDecimal does not loose precision at all. Additionally you can set scale, precision and rounding mode as you prefer.
Upvotes: 0
Reputation: 200138
You probably printed your number with System.out.println(d)
. It will internally call Double.toString(double)
, whose specification states
How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double.
This is because the double
number has no notion of "decimal precision". It is a binary number with fixed binary precision (number of binary digits after the binary point).
Upvotes: 4