0

Could anyone tell me why the second line of code returns NA?

Best regards Tomas

case_when(as.numeric("80")*0.1 == 8.0 ~ TRUE) [1] TRUE

case_when(as.numeric("82")*0.1 == 8.2 ~ TRUE) [1] NA

Tomas Bro
  • 1
  • 1
  • 1
    This is a common issue related to floating point numbers, which manifests in many languages: https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal/9508558#9508558 – Jon Spring Mar 19 '23 at 16:16
  • 1
    Floating points and `==` don't work well... Try `round(as.numeric("82")*0.1, 1) == 8.2` – Andre Wildberg Mar 19 '23 at 16:18
  • 1
    Compare: `sprintf("%.20f",as.numeric("82")*0.1); sprintf("%.20f",8.2)` – Jon Spring Mar 19 '23 at 16:25
  • As stated in the link that @Jon Spring posted, not every floating point number can be represented as a binary value. The value we see is not necessarily the value the computer 'sees'. You can round values, but this is often not suitable if the required level of precision exceeds the amount of rounding required to make a 'match'.. To handle this issue when performing floating point arithmetic, R has the command `all.equal()`. In your case, you could try case_when(isTRUE(all.equal(as.numeric("82")*0.1, 8.2)) ~ TRUE) although isTRUE(all.equal(as.numeric("82")*0.1, 8.2)) does the same thing. – L Tyrone Mar 19 '23 at 19:33

0 Answers0