0

I'm checking if the inputted number is a factor of 100 using the following formula:

100 % n === 0

But when someone enters 0.02 it says that 100 % 0.02 = 0.0199999999999979 which is incorrect.

Why is this happening and how can I solve this?

I also tried using: Math.Abs(100 % 0.02) but it gives me the same result which is 0.0199999999999979.

O S
  • 453
  • 3
  • 14
  • @AhmedAbdelhameed the solution also suggests using `Math.Abs()` but rather than comparing it to `0` I need a tolerance value. However, in my case, it should be equal to `0`, because otherwise it would not be a factor of 100. – O S Mar 20 '20 at 11:36
  • @500-InternalServerError no, the expression is correct. – O S Mar 20 '20 at 11:37
  • @OS: Sorry, I misread the question. – 500 - Internal Server Error Mar 20 '20 at 11:39
  • What did you expect to happen using `Math.Abs()`? It just returns the absolute value of a number but does not round it or something. – Erik T. Mar 20 '20 at 11:44
  • @ErikT. I have no idea, Rider IDE suggested it to me as a solution for `Equality comparison of floating point numbers. Possible loss of precision while rounding values.` The top answer in the post @Ahdmed Abdelhameed linked also makes use of it. – O S Mar 20 '20 at 11:45

2 Answers2

1

0.02 in source code is converted to binary floating-point during compilation. The resulting value is 0.0200000000000000004163336342344337026588618755340576171875.

The remainder of 100 divided by 0.0200000000000000004163336342344337026588618755340576171875 is 0.0199999999999979187481624620659204083494842052459716796875.

To check if a numeral entered by a user is a multiple of 1/100, either use decimal floating-point or examine the characters the user entered. If they contain no non-zero decimal digits after the second decimal place, the number represented is a multiple of 1/100.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
1

Using decimal seems to be working:

100m % 0.02m

Output is

0.00
weichch
  • 9,306
  • 1
  • 13
  • 25