Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 2bed27a

Browse files
mjclydeKent C. Dodds
authored andcommitted
feat(round): function for simple decimal rounding (#94)
1 parent 77d8a86 commit 2bed27a

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import mod from './mod'
3030
import shallowEqual from './shallow-equal'
3131
import swapCase from './swap-case'
3232
import endsWith from './endsWith'
33+
import round from './round'
3334

3435
export {
3536
initArray,
@@ -64,4 +65,5 @@ export {
6465
shallowEqual,
6566
swapCase,
6667
endsWith,
68+
round,
6769
}

src/round.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
export default round
2+
3+
/**
4+
* Original Source: https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary
5+
*
6+
* This method will round a number to the specified decimal places.
7+
*
8+
* @param {number} num - Number to round
9+
* @param {number} decimalPlaces - Decimal places to be rounded to
10+
* @return {number} - Rounded number
11+
*/
12+
13+
function round(num, decimalPlaces) {
14+
if (decimalPlaces < 0) {
15+
throw new Error('decimalPlaces cannot be negative')
16+
}
17+
18+
return +(`${Math.round(+`${num}e+${decimalPlaces}`)}e-${decimalPlaces}`)
19+
}

test/round.test.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import test from 'ava'
2+
import {round} from '../src'
3+
4+
test('Round to 0 places', t => {
5+
t.is(round(1.5, 0), 2)
6+
})
7+
8+
test('Round to 1 places down', t => {
9+
t.is(round(1.54, 1), 1.5)
10+
})
11+
12+
test('Round to 1 places up', t => {
13+
t.is(round(1.55, 1), 1.6)
14+
})
15+
16+
test('Round to 2 places down', t => {
17+
t.is(round(100.334, 2), 100.33)
18+
})
19+
20+
test('Round to 2 places up', t => {
21+
t.is(round(100.335, 2), 100.34)
22+
})
23+
24+
test('Round negative number', t => {
25+
t.is(round(-123.4532, 1), -123.5)
26+
})
27+
28+
test('Throws error if decimal places is negative', t => {
29+
const error = t.throws(() => {
30+
round(5.876, -1)
31+
})
32+
t.is(error.message, 'decimalPlaces cannot be negative')
33+
})
34+

0 commit comments

Comments
 (0)