Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to round to 2 decimal places with typescript?

Tags:

typescript

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?

like image 793
coder-guy-2020 Avatar asked Nov 16 '25 03:11

coder-guy-2020


1 Answers

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));
}
like image 70
Razze Avatar answered Nov 18 '25 21:11

Razze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!