Convert Percent to Decimal using JavaScript

avatar

Borislav Hadzhiev

Thu Dec 23 20212 min read

banner

Photo by Devin Avery

Convert Percent to Decimal using JavaScript #

To convert a percent to a decimal, pass the percent string to the parseFloat() function and divide the result by 100, e.g. parseFloat(percent) / 100. The parseFloat() function parses the provided string and returns a floating point number.

index.js
function toDecimal(percent) { return parseFloat(percent) / 100; } console.log(toDecimal('25%')); // ๐Ÿ‘‰๏ธ 0.25 console.log(toDecimal('55%')); // ๐Ÿ‘‰๏ธ 0.55 console.log(toDecimal('0%')); // ๐Ÿ‘‰๏ธ 0 console.log(toDecimal('100%')); // ๐Ÿ‘‰๏ธ 1

We created a reusable function which takes a percent and converts the value to a decimal.

The parseFloat function takes a string as a parameter and parses the string to a floating point number.

index.js
console.log(parseFloat('25%')); // ๐Ÿ‘‰๏ธ 25 console.log(parseFloat('55%')); // ๐Ÿ‘‰๏ธ 55 console.log(parseFloat('55.5%')); // ๐Ÿ‘‰๏ธ 55.5
If the parseFloat function encounters a character other than a plus +, minus-, numeral 0-9, decimal point ., it returns the value up to that character and ignores the invalid character and the rest of the string.

In our scenario, when the parseFloat method encounters the percent sign %, it short-circuits and returns the floating point number up to that point.

If the first character of the provided string cannot be converted to a number, the parseFloat function returns NaN (not a number).

index.js
console.log(parseFloat('%25')); // ๐Ÿ‘‰๏ธ NaN

The last step is to divide the result of calling the parseFloat function by 100 and get the decimal value.

If you need to handle the scenario where the provided string is not a valid percent, you can check if the result of calling the parseFloat function returns NaN.

This would handle the edge case where you are dividing NaN by 100, which would still return NaN.

index.js
function toDecimal(percent) { const parsed = parseFloat(percent); if (!Number.isNaN(parsed)) { return parseFloat(percent) / 100; } else { return 0; } } console.log(toDecimal('25%')); // ๐Ÿ‘‰๏ธ 0.25 console.log(toDecimal('hello')); // ๐Ÿ‘‰๏ธ 0

We check if the result from calling the parseFloat function is not NaN before dividing it by 100.

In the case that we get an NaN value, we simply return 0.

You might need to handle the else block in a different way depending on your use case.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee