math-precision
.round, .ceil, .floor with precision parameter. E.g.
.round(1.234, 2)
→1.23
This node.js
package gives you a cleaner way to round numbers using precision
. It's simple, lightweight and it relies entirely on JS Math
functions.
It has no dependencies and it works on any node.js
version.
It's a pity not to use it! :)
All world wide web documentation about decimal rounding
in JavaScript,
including Mozilla Docs
lead us to this solution:
E.g. To round 1.2347 with precision 3 you should call:
Math.round(1.2347 * 1000) / 1000 // = 1.235
which is what this package actually does behind the scenes if you call:
.round(1.2347, 3)
(check the source code)
The options are: to write an ugly code, to create a function and copy/paste it everywhere, to export the function from your own utility library or to require this package ... you choose! :)
Anyway there are several npm packages
which does the same thing but I find
this the straightforward way to do it.
It also de deals with negative precision
.round(1234, -2) = 1200
Install
$ npm install math-precision
Examples
.round
var round = round console // 1.23console // 1.24console // 1.2console // 1.246console // 1200console // 13000console // 1console // 1console // NaNconsole // NaN
.ceil
var ceil = ceil console // 1.24console // 1.2console // 1.235console // 1300console // 124000console // 2console // 2console // NaNconsole // NaN
.floor
var floor = floor console // 1.23console // 1.236console // 1.8console // 1800console // 187000console // 1console // 1console // NaNconsole // NaN
using math object
var math = console // 1.24console // 1.24console // 1.23
Test
Simply clone the repo, npm install
, and run npm test