How to format a number as a percent in TypeScript

3 Answers

0 votes
function formatNumberAsPercentage(num : number) {
    return new Intl.NumberFormat('default', {
            style: 'percent',
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
    }).format(num / 100);
}
 
console.log(formatNumberAsPercentage(35.7)); 
console.log(formatNumberAsPercentage(21)); 
 
 
 
   
   
   
/*
run:
   
"35.70%" 
"21.00%"
   
*/

 



answered Apr 19, 2022 by avibootz
0 votes
let n = 27.3;
console.log(parseFloat(n.toString()).toFixed(2) + "%");
 
n = 45;
console.log(parseFloat(n.toString()).toFixed(2) + "%");
 
n = 0;
console.log(parseFloat(n.toString()).toFixed(2) + "%");
 
 
 
   
   
   
/*
run:
   
"27.30%" 
"45.00%" 
"0.00%"
   
*/
 

 



answered Apr 19, 2022 by avibootz
0 votes
function formatNumberAsPercentage(num : number) {
    return Number(num / 100).toLocaleString(undefined,
                  {style: 'percent', minimumFractionDigits:1}); 
}
 
console.log(formatNumberAsPercentage(37.9)); 
console.log(formatNumberAsPercentage(40)); 
 
 
 
   
   
   
/*
run:
   
"37.9%" 
"40.0%" 
   
*/

 



answered Apr 19, 2022 by avibootz
...