This repository was archived by the owner on Feb 20, 2019. It is now read-only.
File tree Expand file tree Collapse file tree 3 files changed +55
-0
lines changed Expand file tree Collapse file tree 3 files changed +55
-0
lines changed Original file line number Diff line number Diff line change @@ -30,6 +30,7 @@ import mod from './mod'
3030import shallowEqual from './shallow-equal'
3131import swapCase from './swap-case'
3232import endsWith from './endsWith'
33+ import round from './round'
3334
3435export {
3536 initArray ,
@@ -64,4 +65,5 @@ export {
6465 shallowEqual ,
6566 swapCase ,
6667 endsWith ,
68+ round ,
6769}
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments