This question already has answers here: How to perform an integer division, and separately get the remainder, in JavaScript? (18 answers) Closed 8 years ago.
Is there any function in Javascript that lets you do integer division, I mean getting division answer in int, not in floating point number.
var x = 455/10;
// Now x is 45.5
// Expected x to be 45
But I want x to be 45. I am trying to eliminate last digit from the number.
parseInt(455/10);
parseInt(x)
var answer = Math.floor(x)
I sincerely hope this will help future searchers when googling for this common question.
var x = parseInt(455/10);
The parseInt() function parses a string and returns an integer. The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number. If the radix parameter is omitted, JavaScript assumes the following: If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal)
number.toString()
call, folllowed by a parse
which is relatively expensive compared to Math.floor
. It is not guaranteed that parseInt
will accept a number
argument.
math.inf // 7 == nan
=> parseInt(Infinity / 7) == NaN
intdiv()
from PHP could be done with something like the following without weird floating point math or other footguns. const intDiv = (a, b) => (a - a % b) / b;
Success story sharing
Math.floor()
returns wrong result. So even Google will return a not-enogh-correct answer. Here: stackoverflow.com/questions/4228356/…Math.floor()
here is just for the case that given number are positive. look at this for more explaination. NormallyparseInt()
is a better choose to get integer part of number or string.