. Advertisement .
..3..
. Advertisement .
..4..
There are a wide range of methods to convert a float number to int in Javascript. Follow this tutorial to find the best solution.
How To Convert A Float Number To Int In Javascript
Method 1: Math.ceil
This method is used to round the number up to the next integer. It is worth noting that the negative number -11 is smaller than -10:
// Positive
Math.ceil(10.1); // 11
Math.ceil(10.5); // 11
Math.ceil(10.9); // 11
// Negative
Math.ceil(-10.1); // -10
Math.ceil(-10.5); // -10
Math.ceil(-10.9); // -10
Method 2: Math.round
Use the math.round function to round the number to the nearest integer:
// Positive
Math.round(10.1); // 10
Math.round(10.5); // 11
Math.round(10.9); // 11
// Negative
Math.round(-10.1); // -10
Math.round(-10.5); // -10
Math.round(-10.9); // -11
Method 3: Math.trunc
Math.trunc removes all fractional digits to return the integer part:
// Positive
Math.trunc(10.1); // 10
Math.trunc(10.5); // 10
Math.trunc(10.9); // 10
// Negative
Math.trunc(-10.1); // -10
Math.trunc(-10.5); // -10
Math.trunc(-10.9); // -10
Method 4: Parselnt
This string argument will likely return a specified radix’s integer. Its integer ranges from 2 to 36:
const radix = 10;
// Positive
parseInt("10.1", radix); // 10
parseInt("10.5", radix); // 10
parseInt("10.9", radix); // 10
// Negative
parseInt("-10.1", radix); // -10
parseInt("-10.5", radix); // -10
parseInt("-10.9", radix); // -10
Remember that if the input starts with “0X” or “0x”, the radix value will be assumed to be 16. Starting with “0” means the radix is 8 or 10. Always specify the radix so that it cannot be omitted by the developers.
Method 5: Bitwise OR
This operator varies based on the type of numbers you are working with. If it is a positive number, this method will round down. On the other hand, a negative number will be rounded up.
Everything after the floating point will also be removed:
// Positive
console.log(10.1 | 0); // 10
console.log(10.5 | 0); // 10
console.log(10.9 | 0); // 10
// Negative
console.log(-10.1 | 0); // -10
console.log(-10.5 | 0); // -10
console.log(-10.9 | 0); // -10
Method 6: Double Bitwise NOT
The double bitwise NOT is basically a combination of two different ones working together instead of being an operator. The -(-(x+1)+1) can be simplified to x so you can receive your original number.
Also, all remaining items after the floating point are truncated:
// Positive
console.log(~~10.1); // 10
console.log(~~10.5); // 10
console.log(~~10.9); // 10
// Negative
console.log(~~-10.1); // -10
console.log(~~-10.5); // -10
console.log(~~-10.9); // -10
Conclusion
The post has offered various methods to convert a float number to int in Javascript. For more available ways, check and choose the one that suits your case from this article.
Leave a comment