Convert a float number to integer in JavaScript
Question:
How to convert a float number to integer in JavaScript? Answer:
const num1 = Math.trunc(11.95);
const num2 = Math.trunc(18.05);
console.log(num1 + ' - ' + num2); // 11 - 18
Description:
If you want the integer (whole) part of a float without rounding, you can use the Math.trunc
function. The Math.trunc()
function returns the integer part of a number by removing any fractional digits.
Unlike the other three Math methods: Math.floor()
, Math.ceil()
and Math.round()
, the way Math.trunc()
works is very simple. It truncates (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number.
Reference:
Math.truncate reference
Share "How to convert a float number to integer in JavaScript?"
Related snippets:
- Check if number is odd or even in JavaScript
- Round a number in JavaScript
- Get the absolute value of a number in JavaScript
- Generate random date with JavaScript
- Generate random string in JavaScript
- Generate a random number with fixed length using JavaScript
- Generate a random number in a range with JavaScript
- Get the minimum value in an array using JavaScript
- Get the maximum value in an array using JavaScript
- Convert a float number to integer in JavaScript
- Round a number to the nearest 10 using JavaScript
- Round down a number in JavaScript
- Round up a number in JavaScript
Tags:
convert, float, int, integer, whole Technical term:
Convert a float number to integer in JavaScript