Author -  Sai gowtham

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 :

  1. Pass the number to a parseFloat() method.

  2. Call the toFixed() method on a result.

  3. 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:

  1. The first one is locale string which defaults to the user machine language or you can use like this ‘en-US’.

  2. 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.

References

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY