From d9821bfafdfe3cbcde5fb32fda9eb94736f762d1 Mon Sep 17 00:00:00 2001 From: Eric Wyne Date: Thu, 14 Dec 2017 13:09:08 -0800 Subject: [PATCH] round number to n digits --- snippets/round-number-to-n-digits.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 snippets/round-number-to-n-digits.md diff --git a/snippets/round-number-to-n-digits.md b/snippets/round-number-to-n-digits.md new file mode 100644 index 000000000..0c33b5b4f --- /dev/null +++ b/snippets/round-number-to-n-digits.md @@ -0,0 +1,9 @@ +### Round number to n digits + +Correctly rounds a number to the specified number of digits. + +```js +const round = (n, decimals = 0) => + Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`) +// round(1.005, 2) -> 1.01 +```