-1

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?

  • 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

3 Answers3

0

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
  • 7,680
  • 10
  • 58
  • 123
-1

I have used following code to round to 2 decimal places

(Math.round(val * 100) / 100).toFixed(2);
Chamika
  • 69
  • 4
-1

It's just js fn with types:

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

Read docs

zemil
  • 920
  • 1
  • 7
  • 21