ChatGPT解决这个技术问题 Extra ChatGPT

How to do integer division in javascript (Getting division answer in int not float)? [duplicate]

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.

Have you tried parseInt or Math.floor?
@SB how ca i use parseInt for this problem.
@Nakib, parseInt(455/10);
Nakib - you could try parseInt(x)
The best way now would be: var x = Math.trunc(455/10);

L
Lesmana
var answer = Math.floor(x)

I sincerely hope this will help future searchers when googling for this common question.


thanks i googled it but couldn't find, thanks anyway :)
I find significant irony that this is the top answer in my google search for how to solve this problem.
I find that this answer is even not correct all the time. If result is negative number, Math.floor() returns wrong result. So even Google will return a not-enogh-correct answer. Here: stackoverflow.com/questions/4228356/…
usage of Math.floor() here is just for the case that given number are positive. look at this for more explaination. Normally parseInt() is a better choose to get integer part of number or string.
Math.trunc() address the negative value problem. In fact, trunc is what you need if you just want to remove decimal part. stackoverflow.com/a/22307150/5876282
S
ST3
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)


This is inefficient because it has an implicit 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.
However this emulates the behavior of python3: math.inf // 7 == nan => parseInt(Infinity / 7) == NaN
Emulating 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;