BigDecimal – Random IT Utensils https://blog.adamfurmanek.pl IT, operating systems, maths, and more. Thu, 09 May 2019 01:16:14 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.2 Comparing numbers is hard https://blog.adamfurmanek.pl/2019/08/17/comparing-numbers-is-hard/ https://blog.adamfurmanek.pl/2019/08/17/comparing-numbers-is-hard/#respond Sat, 17 Aug 2019 08:00:21 +0000 https://blog.adamfurmanek.pl/?p=3057 Continue reading Comparing numbers is hard]]> We know that to compare floating point values we should use epsilon and not just compare bits. We may run into similar issues when comparing BigDecimal in Java:

BigDecimal a = BigDecimal.valueOf(0);
BigDecimal b = BigDecimal.valueOf(Double.valueOf(0));
System.out.println(a.equals(b));

What is the output? Of course it is false, otherwise I wouldn’t write this post. This is because BigDecimal includes scale:

Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

So we should use this:

System.out.println(a.compareTo(b));

and then the result is as we expect.

]]>
https://blog.adamfurmanek.pl/2019/08/17/comparing-numbers-is-hard/feed/ 0