Why are there precision problems in JavaScript

Integer division with remainder in JavaScript?

JavaScript calculates the lower bound of the negative numbers and the rest of the non-integer numbers according to the mathematical definitions.

FLOOR is defined as "the largest integer that is smaller than the parameter", so:

  • positive numbers: FLOOR (X) = integer part of X;
  • negative numbers: FLOOR (X) = integer part of X minus 1 (because it has to be LESS than the parameter, i.e. more negative!)

REMAINDER is defined as the "remainder" of a division (Euclidean arithmetic). If the dividend is not an integer, then the quotient is usually not an integer either, i.e. there is no remainder, but when the quotient is forced to be an integer (and this is when someone tries to find the remainder or that To get module of a floating point number), a non-integer number will of course be left.

JavaScript calculates everything as expected, so the programmer must be careful to ask the correct questions (and people should be careful to answer what is asked!) Yarin's first question was NOT "What is the integer division of X by Y ", but instead" the integer number of times a given integer goes into another ". For positive numbers, the answer is the same for both, but not for negative numbers, since the integer division (dividend by divisor) -1 is less than the number of times one number (divisor) goes into another (dividend). In other words, FLOOR returns the correct answer for an integer division of a negative number, but Yarin didn't ask that!

gammax answered correctly, this code works as requested by Yarin. On the other hand, Samuel is wrong, he didn't do the math, or he would have seen it work (also, he didn't say what the divider of his example was, but I hope it was 3):

Remainder = X% Y = -100% 3 = -1

GoesInto = (X - remainder) / Y = (-100 - -1) / 3 = -99 / 3 = -33

By the way, I tested the code on Firefox 27.0.1. It worked as expected with positive and negative numbers, as well as non-integer values, for both dividend and divisor. Example:

-100.34 / 3.57: GoesInto = -28, remainder = -0.3800000000000079

Yes, I noticed there was a precision issue, but I haven't had time to check (I don't know if it's a problem with Firefox, Windows 7, or my CPU's CPU CPU). However, the gammax code works fine for Yarin's question, which contains only whole numbers.