Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong Decimal Converting from Double to String in java

I have A String that is formatted correctly to be cast to a double and it works fine for most decimals. The issue is that for .33, .67, and possibly others I haven't tested, the decimal becomes something like .6700000000002, or .329999999998. I understand why this happens but does any one have a suggestion to fix it.

like image 661
KBusc Avatar asked Aug 05 '26 11:08

KBusc


2 Answers

It's a result of IEEE-754 rounding rules, some numbers cannot be represented precisely in two's complement. For example, 1/10 is not precisely representable.

You can add more precision (but not infinite) by using BigDecimal.

BigDecimal oneTenth = new BigDecimal("1").divide(new BigDecimal("10"));
System.out.println(oneTenth);

Which outputs 0.1

like image 110
Elliott Frisch Avatar answered Aug 07 '26 01:08

Elliott Frisch


Some decimal numbers can not be represented accurately with the internal base 2 machine representation.

like image 40
user3146587 Avatar answered Aug 06 '26 23:08

user3146587



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!