How to format numbers as percentage values in JavaScript?

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.


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)+"%");

Modern JS:

For any of these, remove * 100 if you start with a whole number instead of decimal.

Basic

const displayPercent = (percent) => `${(percent * 100).toFixed(2)}%`;

Dynamic with safe handling for undefined values

const displayPercent = (percent, fallback, digits = 2) =>
  (percent === null || percent === undefined) ? fallback : `${(percent * 100).toFixed(digits)}%`;

Typescript:

const displayPercent = (percent: number) => `${(percent * 100).toFixed(2)}%`;

Tags:

Javascript