14

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?

coder-guy-2020
  • 167
  • 1
  • 1
  • 4
  • Does this answer your question? [Format number to always show 2 decimal places](https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places) – Baruch Dec 25 '19 at 16:26
  • 1
    Does this answer your question? [Round to at most 2 decimal places (only if necessary)](https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary) – chrisbyte Dec 25 '19 at 16:27
  • How does rounding produce 123.46 from 123.45? – Terry Dec 25 '19 at 16:29

4 Answers4

19

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));
}
Razze
  • 4,124
  • 3
  • 16
  • 23
5

I have used following code to round to 2 decimal places

(Math.round(val * 100) / 100).toFixed(2);
Chamika
  • 129
  • 4
2

Idk why everything in web-world turns to circus but it seems there is no out-of-the-box solution. I found this blog and it works as far as i could test it:https://expertcodeblog.wordpress.com/2018/02/12/typescript-javascript-round-number-by-decimal-pecision/

  public round(number: number, precision: number) {
    if (precision < 0) {
      let factor = Math.pow(10, precision);
      return Math.round(number * factor) / factor;
    }
    else
      return +(Math.round(Number(number + "e+" + precision)) +
        "e-" + precision);
  }
}

Boppity Bop
  • 9,613
  • 13
  • 72
  • 151
0

For the easiest-to-remember solution but sometimes it can be invalid preceding:

function round(num: number): number {
  return Math.round(num * 100) / 100;
}

For more specific and to ensure things like 1.005 round correctly:

function round(value: number, decimals = 2): number {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
zemil
  • 3,235
  • 2
  • 24
  • 33