Categories
JavaScript Answers

How to Make a Number a Percentage with JavaScript?

Spread the love

We can make a number a percentage with basic arithmetic operators.

For instance, we can write:

const number1 = 4.954848;
const number2 = 5.9797;
console.log(Math.floor((number1 / number2) * 100));

to get the percentage of number1 of number2 by dividing number1 by number2 .

Then we multiply that by 100 to get the percentage point.

And then we call Math.floor to round the returned result down to the nearest integer.

We should get 82 from the console log.

Make a Number a Percentage with JavaScript with the toLocaleString Method

Also, we can make a number a percentage with the toLocaleString method.

For instance, we can write:

const number1 = 4.954848;
const number2 = 5.9797;
const percentage = (number1 / number2).toLocaleString("en", {
  style: "percent"
})
console.log(percentage);

We divide number1 by number2 .

Then we call toLocaleString on the returned result with the 'en' locale and an object with style set to 'percent' to return a string with the percentage of number1 divided by number2 .

We should get '83%' from the console log.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *