Last updated on September 20, 2023
In JavaScript, the built-in function parseInt() converts float or string value into an integer. It takes two parameters: the first is required and the second is optional.
The parseInt() function converts its first parameter into an integer value. It returns a Number (converted value) when it converts the numeric values in the string otherwise it returns NaN.
Syntax
parseInt(param1, param2);
Usage
To begin with, let’s create a variable and assign a float value to it.
let flowerPrice = 7.80;
console.log(flowerPrice);
// Output: 7.8
Above, we created a variable with a float value and print it through the console.log() function that returns the assigned value. Next, we need to check if flowerPrice
data type is float. To do that we can use JavaScript’s typeof operator that helps us to know the data type of a value.
console.log(typeof flowerPrice);
// Output: number
We have the number in the console log returned by typeof operator for flowerPrice
. In the next step, we need to use the parseInt() function for converting the float value into an integer.
convertIntoInteger = parseInt(flowerPrice);
console.log( convertIntoInteger);
// Output: 7
The parseInt() function converted flowerPrice
variable value into an integer which is assigned to the new variable convertIntoInteger
. In the console log, the convertIntoInteger
variable returned an integer value which proves that the parseInt() function converted the float value into integer.
Conclusion
This article demonstrates converting float values into integers in JavaScript. To do that, it takes the float value in the first parameter and converts it into an integer or a number.