How to format numbers as percentage values in JavaScript?

Viewed 71708

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%
6 Answers

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)}%`;

I had decimal values such as 0.01235 and 0.016858542 that I wanted to convert to percentages 1.235% and 1.6858542% respectively. I thought it was going to be easy, just calculate (0.012858542 * 100) and I'm good to go. I was wrong, (0.012858542 * 100) = 1.2858542000000002 because of decimal conversion.

Let's add toFixed() to the calculation and I end up with the right value.

(0.012858542*100).toFixed(7)    // returns "1.2858542"
(0.01235*100).toFixed(7)        // returns "1.2350000"

I don't like to show four trailing zeros when they're unnecessary. One solution I thought about was to use replace() to remove all trailing zeros but I ended up using Numeral.js instead because it does all the work for me while it's lightweight. I can recommend it!

import numeral from 'numeral';

numeral(0.012858542 * 100).format('0.00[0000]') // returns "1.2858542"
numeral(0.01235 * 100).format('0.00[0000]')     // returns "1.235"

Transform number to percentage with X float decimal positions

function toPercent(number, float) {
  var percent = parseFloat(number * 100).toFixed(float) + "%";
  return percent;
}
Related