How to format a number as a percent in JavaScript

3 Answers

0 votes
function formatNumberAsPercentage(num) {
  	return new Intl.NumberFormat('default', {
    		style: 'percent',
    		minimumFractionDigits: 2,
    		maximumFractionDigits: 2,
  	}).format(num / 100);
}

console.log(formatNumberAsPercentage(25.6)); 
console.log(formatNumberAsPercentage(30)); 



  
  
  
/*
run:
  
"25.60%"
"30.00%"
  
*/

 



answered Apr 19, 2022 by avibootz
0 votes
let n = 25.6;
console.log(parseFloat(n).toFixed(2) + "%");

n = 30;
console.log(parseFloat(n).toFixed(2) + "%");

n = 0;
console.log(parseFloat(n).toFixed(2) + "%");



  
  
  
/*
run:
  
"25.60%"
"30.00%"
"0.00%"
  
*/

 



answered Apr 19, 2022 by avibootz
0 votes
function formatNumberAsPercentage(num) {
  	return Number(num / 100).toLocaleString(undefined,
                  {style: 'percent', minimumFractionDigits:1}); 
}

console.log(formatNumberAsPercentage(25.6)); 
console.log(formatNumberAsPercentage(30)); 



  
  
  
/*
run:
  
"25.6%"
"30.0%"
  
*/

 



answered Apr 19, 2022 by avibootz

Related questions

3 answers 195 views
3 answers 190 views
1 answer 129 views
2 answers 244 views
2 answers 231 views
1 answer 174 views
2 answers 129 views
...