JavaScript - How to Format a number to percentage
In this tutorial, we are going to learn about how to format a number to percentage in JavaScript with the help of examples.
Consider we have a number like this.
const num = 12
Now, we need to format the above number to percentage like this 12 %
.
Using toFixed() method
To format a number to percentage in JavaScript :
-
Pass the number to a parseFloat() method.
-
Call the toFixed() method on a result.
-
Add the percentage
%
to the final output.
Here is an example:
const num = 12;
const percentage = parseFloat(num).toFixed(1) + "%"
console.log(percentage);
Output:
"12.0 %"
The parseFloat()
function takes the string as an argument and parses it to a float point number.
The toFixed()
method takes the number of digits as argument and formats the number into the mentioned decimal places. By default the toFixed()
method removes the fractional part.
Note: The toFixed()
returns string representation of number.
Using the Intl.NumberFormat() constructor
We can also use the Intl.NumberFormat() constructor to format the number to a constructor.
Here is an example:
const num = 120;
const percentage = new Intl.NumberFormat('default', {
style: 'percent',
minimumFractionDigits: 1,
maximumFractionDigits: 1,
}).format(num / 100);
console.log(percentage);
Output:
"120%"
The Intl.NumberFormat() function takes two arguments:
-
The first one is locale string which defaults to the user machine language or you can use like this ‘en-US’.
-
The second one is formating object. it contains
style
property which is percentage in our case and how many number of minimum and maximum fractional digits we need to be specificed.