Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format numbers as percentage values in JavaScript?

Tags:

javascript

Was using ExtJS for formatting numbers to percentage earlier. Now as we are not using ExtJS anymore same has to be accomplished using normal JavaScript.

Need a method that will take number and format (usually in %) and convert that number to that format.

0 -> 0.00% = 0.00% 25 -> 0.00% = 25.00% 50 -> 0.00% = 50.00% 150 -> 0.00% = 150.00% 
like image 875
BeingSuman Avatar asked Jul 18 '17 09:07

BeingSuman


People also ask

How do I make a percentage in JavaScript?

Make a Number a Percentage with JavaScript with Arithmetic 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 .

How do you format a number to a percent?

Percentages are calculated by using the equation amount / total = percentage. For example, if a cell contains the formula =10/100, the result of that calculation is 0.1. If you then format 0.1 as a percentage, the number will be correctly displayed as 10%.

How do you change a number to a percent in typescript?

floor((number1 / number2) * 100)); //w00t! alert(~~((number1 / number2) * 100)); as the Math.

How do you format numbers in JavaScript?

JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl. NumberFormat() method to format the number with currency.


2 Answers

Here is what you need.

var x=150; console.log(parseFloat(x).toFixed(2)+"%"); x=0; console.log(parseFloat(x).toFixed(2)+"%"); x=10 console.log(parseFloat(x).toFixed(2)+"%");
like image 112
Manish Avatar answered Oct 25 '22 06:10

Manish


You can use Number.toLocaleString():

var num=25;  var s = Number(num/100).toLocaleString(undefined,{style: 'percent', minimumFractionDigits:2});   console.log(s);
No '%' sign needed, output is:
25.00% 

See documentation for toLocaleString() for more options for the format object parameter.

like image 35
wrlee Avatar answered Oct 25 '22 05:10

wrlee