Borislav Hadzhiev
Last updated: Dec 23, 2021
Check out my new book
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.
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.
console.log(parseFloat('25%')); // 👉️ 25 console.log(parseFloat('55%')); // 👉️ 55 console.log(parseFloat('55.5%')); // 👉️ 55.5
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).
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
.
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.