Do all the things like ++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatarSign Up
b3b3489869dDoes the BidDezimal consstructor only take floats?
Pickman49969dNo, of course. It's just the BigDecimal class, you can find the APIs online.
It's not the constructor being wrong, it's the one who uses it that does it wrong. That's all that needs to be said.
Otherwise, RTFM or consider accuracy issues within floating-point numerical datatypes:
"The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding."
@filthyranter this is the root of the problem. Well done. But how to explain its manifestation? Why do the other two prints exhibit the correct behaviour? Do they do that always (they don't)? How do we find a number that shows this?
Also notice how the author of this code was actually lazy and used BigDecimal to round the numbers instead if writing his own function.
@Pickman The issue is that the new BigDecimal() constructor takes the exact value of the double, so the technically "more correct" way.
The other two methods use the string representation.
So if there's a difference, the first and the latter two will be different (but of course, that is not always the case)
The rounding using .setScale just more visibly shows that effect, tbh.
gruff66568dThis is like 0 != 0m in c#
@filthyranter not quite, the second two cast the double to float and then use the string representation of that float. This means that is equivalent to using the first constructor (well its version that takes a float) by casting the double to float. What's funny is that this does not prevent "unexpected" behaviour.
In fact if that double would be a float there would not be this "error".
Your Job Suck?
Take a quick quiz from Triplebyte to skip the job search hassles and jump to final interviews at hot tech firms
Get a Better Job