I know this has been asked many times before, and we've settled for a solution on rounding amounts (currency) with two decimals as:
const myCurrencyAmount = Number(Math.round(totalAmount + 'e' + 2) + 'e-' + 2)
However, it is now very, very close to 2022 and Elon Musk is about to send people to Mars (well, the moon first, but...) so surely there must be a better way to round (safely!) in Node.js by now...???
The above solution has been working fine now for some time (years) but as soon as you want to start adding or do calculations using two decimals (like in invoices for example) it quickly becomes arduous to keep track of rounding all number, all the time!
Because in Node.js, of course, if you round a number once, to two decimals, it's not going to remember that and use its floating point again the next time you want to read the variable messing up your calculations anew...
And for you, who thinks but why not simply use .toFixed(2)
, I can tell you that the world of floats will bring you some hurt sooner or later... or, in the meantime just enjoy these lovely samples:
const num = 35.855;
console.log(num.toFixed(2));
// LOGS: 35.85
const num2 = 1.005;
console.log(num2.toFixed(2));
// LOGS: 1.00
Then imagine summarizing a few thousand invoice lines with many thousands in quantity and see how much those rounding errors throws you off...
Please note that I am not asking about floating points (as I do understand them) I am simply asking for a solution with less characters to write...