vend-number
A collection of utility methods for floating point Number operations
vend-number
is a vend-flavoured wrapper for BigNumber.js.
Instead of constructing BigNumber
objects from your numbers and performing operations on them within your app, this module provides a set of simplified math utilities that take simple Number
or String
types, and use BigNumber
operations for accuracy behind the scenes.
API
VendNumber
is an extension of the BigNumber
class.
import VendNumber from 'vend-number'
const num = new VendNumber('123.456')
num.round(2)
num instanceof BigNumber
There is a shortcut method of construction in VendNumber.vn
:
import VendNumber, { vn } from 'vend-number'
const num = vn(123.456)
num.round(2)
num instanceof VendNumber
Math operations
The following static methods can take any number of values and perform the operation on each of them in the specified order.
Add a list of values
VendNumber.add(1, 2, 3)
Subtract a list of values
VendNumber.subtract(2, 1)
Multiply a list of values
VendNumber.multiply(2, 2)
Divide a list of values
VendNumber.divide(10, 2)
Keep in mind when using the VendNumber
math functions that when performing multiple calculations you will need to make
sure the execution order is correct.
Native JS will execute in order of BEDMAS automatically, whereas with these methods, you have to make sure of this manually.
E.g.
4 * 5 + 3
multiply(4, add(5, 3))
You need to take into account the order in which the functions will be executed, so in this case it should be:
add(3, multiply(4, 5))
Rounding and formatting
Round a value to a specified number of decimal points. The default rounding mode is ROUND_HALF_UP
, the 'Round Half
Away From Zero' tie-breaking rule.
VendNumber.round(5.545333, 2)
Rounding modes
You can specify any of the Big Number rounding modes to the round
function. These are available via VendNumber.ROUNDING_METHODS
.
import VendNumber, { ROUNDING_MODES } from 'vend-number'
VendNumber.round(5.545333, 2, ROUNDING_MODES.ROUND_DOWN)
isFinite
A static equivalent to BigNumber.isFinite
that reports false
for non-numeric values.
VendNumber.isFinite(null)
VendNumber.isFinite('')
VendNumber.isFinite(Infinity)
VendNumber.isFinite(0)
VendNumber.isFinite(Number.MAX_VALUE)
VendNumber.isFinite('-123.456')
sumBy
Calculates the sum of all items in a collection based on a property name.
Accepts the following parameters:
Array
an array of items to loop through.String
a property name to sum by.Number
an optional decimal points number to round the sum value to (defaults to 2 d.p.).
Example:
VendNumber.sumBy([], '')
VendNumber.sumBy([{ a: 1 }, { a: 2 }], 'a')
VendNumber.sumBy([{ a: 1.4222 }, { a: 2.1115 }], 'a', 3)
Contributing
Build
npm run build
Test
npm test
Watch
To watch for changes, build them and run the tests:
npm run watch
License
MIT © Vend