get the integer after decimal in javascript

In JavaScript, there are a couple of ways to get the integer after a decimal. The easiest way is to use the Math.round() and Math.floor() methods.


// Use Math.round()
// Round to the nearest integer
let number = 4.6;
let roundedNumber = Math.round(number); 
console.log(roundedNumber); // Output: 5

// Use Math.floor()
// Round down to the nearest integer
let number = 4.6;
let roundedNumber = Math.floor(number); 
console.log(roundedNumber); // Output: 4

You can also use the parseInt() and parseFloat() methods to get the integer after the decimal.


// Use parseInt()
// Parse a string and return an integer
let number = "4.6";
let roundedNumber = parseInt(number); 
console.log(roundedNumber); // Output: 4

// Use parseFloat()
// Parse a string and return a float
let number = "4.6";
let roundedNumber = parseFloat(number); 
console.log(roundedNumber); // Output: 4.6

You can also use the toFixed() method to convert a number to a string, keeping a specified number of decimals.


// Use toFixed()
// Return a number as a string, keeping a specified number of decimals
let number = 4.6;
let roundedNumber = number.toFixed(0); 
console.log(roundedNumber); // Output: 5

These are just a few of the ways you can get the integer after a decimal in JavaScript. Depending on your requirements, you can choose the best solution for your project.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe