Computer >> Computer tutorials >  >> Programming >> Javascript

Retrieving the decimal part only of a number in JavaScript


Problem

We are required to write a JavaScript function that takes in a number. Our function should pick and return the part of the number after the decimal point(.)

Example

Following is the code −

const num = 435.43436;
const retrieveDecimalPart = (num = 1) => {
   const str = String(num);
   let [_, decimal] = str.split('.');
   const divisor = Math.pow(10, decimal.length)
   decimal = +decimal;
   return decimal / divisor;
};
console.log(retrieveDecimalPart(num));

Output

Following is the console output −

0.43436