Programming Tips - javaScript: limit the number of decimal digits when displaying a number

Date: 2018apr7 Updated: 2024mar16 Language: javaScript Keywords: dollars, cents, financial, round Q. javaScript: limit the number of decimal digits when displaying a number A. Use Number.toFixed() like this
const n = 1.23456789; console.log(n.toFixed(2));
Will display
1.23
Note that toFixed() requires a number and it returns a string. Here's a function with some robustness:
function twoDecimal(num) { if (typeof(num) == 'string') num = parseFloat(num) return num.toFixed(2); }
If you want zero decimal digits:
function zeroDecimal(num) { if (typeof(num) == 'string') num = parseFloat(num) return num.toFixed(); }
More info https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed