# npm

Need private packages and team management tools?Check out npm Teams »

## @taoqf/money-math

3.0.4 • Public • Published

# What does it do?

Adds, multiplies the currency amounts, and calculates percentages of amounts. The result of each of those operations is also an amount: a string, strictly matching the `/^\-?\d+\.\d\d\$/` pattern, like "0.25", "1000.00", or "-42.10".

Amounts on input and output are arbitrary large and precise:

``````99999999999999999999999999999999999999999999999999999999999999999999999999999999.99
+
0.01
=
100000000000000000000000000000000000000000000000000000000000000000000000000000000.00
``````

However, in cases when the division is involved — like for percentage calculation — the result is rounded to the whole cent.

As a bonus feature, there's a simple formatting function for amounts in the following currencies:

• CHF
• EUR
• GBP
• JPY
• LTL
• PLN
• SEK
• SKK
• UAH
• USD

# Why does it exist?

Because storing currency amounts in floats is a really bad idea

# Install

Works both on Node and in the browser.

# Node/Browserify/Webpack

``````\$ npm install --save money-math
``````

# Usage

And last, but not least :)

Which we use for bills in CHF that are required by law to be 0 (mod 5).

# An important note on the amount "data type"

The amount strings are expected to strictly adhere to the format described by the regular expression noted above. Thus, for example, it must be:

• `"10.10"`, not `"10.1"`, not `"10.100"`;
• `"10.00"`, not `10`, not `"10"`, not `"10.0"`.

That's a precondition for any of the API functions accepting amount arguments to work correctly. I understand that it may be confusing to some of new users; but I believe that's an optimally pragmatic way to mimic, by convention, an algebraic data type in idiomatic JavaScript -- a (very) dynamically typed language.

Luckily, you can always move your arbitrary float value into the amounts field with `money.floatToAmount(...)`. Once all the values are amounts, money-math guarantees that all the field operations keep the results withing the field. Classic algebra.

A thoughtful reader may ask, why have `money.floatToAmount()`, when there's the `Number.prototype.toFixed(2)`? Well, because:

Floats are such floats...

## Keywords

### Install

`npm i @taoqf/money-math`

0

3.0.4

MIT

40.4 kB

12

### Repository

github.com/ikr/money-math