How to format a number with two decimals places in JavaScript

2 Answers

0 votes
let num1 = 3.7;
let num2 = 12.8941;
let num3 = 3.005;
let num4 = 8.245;

console.log(num1.toFixed(2));
console.log(num2.toFixed(2));
console.log(num3.toFixed(2));
console.log(num4.toFixed(2));

  
    
    
/*
run:

"3.70"
"12.89"
"3.00"
"8.24"
    
*/

 



answered Jan 29, 2021 by avibootz
edited Jan 29, 2021 by avibootz
0 votes
const formatTwoDecimals = (num, decimals) => num.toLocaleString('en-US', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});

let num1 = 3.7;
let num2 = 12.8941;
let num3 = 3.005;
let num4 = 8.245;

console.log(formatTwoDecimals(num1));
console.log(formatTwoDecimals(num2));
console.log(formatTwoDecimals(num3));
console.log(formatTwoDecimals(num4));

  
    
    
/*
run:

"3.70"
"12.89"
"3.01"
"8.25"
    
*/

 



answered Jan 29, 2021 by avibootz

Related questions

2 answers 153 views
1 answer 176 views
1 answer 152 views
1 answer 132 views
1 answer 113 views
1 answer 132 views
...