Percentage to Decimal in JavaScript

In this tutorial, we will learn how to convert a percentage to decimal in JavaScript.

Percentage to decimal in JavaScript

We can use the parseFloat() method to convert the a percentage string '90%' to decimal 0.90

This can be done by creating a function that will take the percentage as input, pass it to the parseFloat(), and then divide the output by 100.

const percentToDecimal = (percentStr) => {
  return parseFloat(percentStr) / 100;  
};

console.log(percentToDecimal('90%')); //0.9
console.log(percentToDecimal('9%'));  //0.09
console.log(percentToDecimal('22.22%')); //0.22219999999999998

parseFloat() takes a string value as input and it will trim everything after the +, -, ., 0-9 characters.

So if the strings start with any of the above, it will trim the characters after them and return the values before it as a number.

console.log(parseFloat("90%")); // 90

Once we have got the number we divide it by 100 to get the decimal value.

console.log(90 / 100); // 0.90 

Handling the NaN values while converting percentage to decimal in JavaScript

In case, the string passed to the parseFloat() is starting with different characters it will throw NaN (Not a Number) error.

console.log(parseFloat("%90")); // NaN

To handle that we can add an addition check during the conversion of percent to decimal.

const percentToDecimal = (percentStr) => {
  const  afterFloatParsing = parseFloat(percentStr);
  return isNaN(afterFloatParsing) ? 0 : afterFloatParsing / 100;
};

console.log(percentToDecimal('90%')); // 0.9
console.log(percentToDecimal('9%')); // 0.09
console.log(percentToDecimal('22.22%')); // 0.22219999999999998
console.log(percentToDecimal('%22.22')); // 0

Also see, Format a number to percentage in JavaScript.