I need to write a function in TypeScript which can round a number to 2 decimal places. For example:
123.456 => should return 123.46
123.3210 => should return 123.32
Can you identify the TypeScript function that I can use to accomplish this? Alternatively, is there is a commonly used third party library used for this, then what library and function should I use?
You can use toFixed, it rounds but it returns a string. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
So your function body will most likely end up with something like
function round(num: number, fractionDigits: number): number {
return Number(num.toFixed(fractionDigits));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With