Get the decimal part of a number in JavaScript

Let's suppose that we have a decimal number and we want to split in two parts (ones and decimals):

// we want to get firstNumber = 8 and secondNumber = 9
let number = 8.9;

We can do it but converting the number into a string and then splitting it:

// Decimal number
let number = 8.9;

// Convert it into a string
let string = number.toString();

// Split the dot
let array = string.split('.');

// Get both numbers
// The '+' sign transforms the string into a number again
let firstNumber  = +array[0]; // 8
let secondNumber = +array[1]; // 9

We can do it in one line of code as well:

let [firstNumber, secondNumber] = [+number.toString().split('.')[0], +number.toString().split('.')[1]];

// console.log(firstNumber) → 8
// console.log(secondNumber) → 9

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.