Sunday, May 20, 2018

Number.isInteger


This is a new method coming in ES6, and it wasn’t previously available as a global function. The isInteger method returns true if the provided value is a finite number that doesn’t have a decimal part.
console.log(Number.isInteger(Infinity)) // <- false
console.log(Number.isInteger(-Infinity)) // <- false
console.log(Number.isInteger(NaN)) // <- false
console.log(Number.isInteger(null)) // <- false
console.log(Number.isInteger(0)) // <- true
console.log(Number.isInteger(-10)) // <- true
console.log(Number.isInteger(10.3)) // <- false
You might want to consider the following code snippet as a ponyfill for Number.isInteger. The modulus operator returns the remainder of dividing the same operands. If we divide by one, we’re effectively getting the decimal part. If that’s 0, then it means the number is an integer.
function numberIsInteger(value) {
  return Number.isFinite(value) && value % 1 === 0
}
Next up we’ll dive into floating-point arithmetic, which is well-documented as having interesting corner cases.

No comments:

Post a Comment

Remote Hybrid and Office work