From 40843b252c636d54ebeb199e9a83a4030dc66009 Mon Sep 17 00:00:00 2001 From: Eric Wyne Date: Thu, 14 Dec 2017 13:09:08 -0800 Subject: [PATCH 1/2] 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 +``` From a2ab684cfc1de4fdc87e27e8ba0a2a8c193db530 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Thu, 14 Dec 2017 23:15:34 +0200 Subject: [PATCH 2/2] Update round-number-to-n-digits.md --- snippets/round-number-to-n-digits.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/snippets/round-number-to-n-digits.md b/snippets/round-number-to-n-digits.md index 0c33b5b4f..a35308ce0 100644 --- a/snippets/round-number-to-n-digits.md +++ b/snippets/round-number-to-n-digits.md @@ -1,9 +1,9 @@ ### Round number to n digits -Correctly rounds a number to the specified number of digits. +Use `Math.round()` and template literals to round the number to the specified number of digits. +Omit the second argument, `decimals` to round to an integer. ```js -const round = (n, decimals = 0) => - Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`) +const round = (n, decimals=0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); // round(1.005, 2) -> 1.01 ```