how to eliminate decimals in js
How to eliminate decimals in JS
If you are working with numbers in JavaScript, you might come across situations where you need to eliminate the decimal part of a number. There are a couple of ways to do this:
1. Using Math.floor()
One way to eliminate decimals is to use the Math.floor() method. This method rounds down a number to the nearest integer, effectively eliminating the decimal part.
let num = 3.14159;
let roundedNum = Math.floor(num);
console.log(roundedNum); // Output: 3
In the code above, we declare a variable 'num' and assign it the value of 3.14159. We then use the Math.floor() method to round down 'num' to the nearest integer and assign the result to a new variable 'roundedNum'. Finally, we log the value of 'roundedNum' to the console, which should be 3.
2. Using parseInt()
Another way to eliminate decimals is to use the parseInt() function. This function parses a string and returns an integer.
let numString = "3.14159";
let num = parseInt(numString);
console.log(num); // Output: 3
In the code above, we declare a variable 'numString' and assign it the string value of "3.14159". We then use the parseInt() function to parse the string and convert it to an integer, which we assign to a new variable 'num'. Finally, we log the value of 'num' to the console, which should be 3.
Both Math.floor() and parseInt() can be used to eliminate decimals in JavaScript. The choice between the two may depend on the specific requirements of your application.