16

I am trying to deal with JavaScript values such as 23.45, but I want to be able to do mathematical operations on these values (addition, subtraction, multiplication, division) without running into floating point issues. Yes, I might need to round the results sometimes, but I would like it to give reasonable answers.

Consider this in JavaScript:

24.56 * .3

Yields

7.36799999999

I would like it to come out with 7.368.

Most languages have either a decimal or currency data type to deal with this. Has anyone built a class that can handle this sort of data effectively, or is there any other solution for dealing with these sorts of numbers without having to constantly adjust for floating point errors?

8 Answers 8

10

Integers.

There is no need to use floating-point for currency. Use fixed-point, where the number of decimal points is 0.

You count in pennies (or possibly in tenths of pennies).

10
  • 5
    @Jeff: They did. They lived thousands of years ago and they discovered how to multiply by 100. May 11, 2011 at 16:32
  • 1
    The question is about javascript. JS don't have integers, everything is doubles. stackoverflow.com/a/3605946/446536
    – geon
    Sep 21, 2012 at 14:06
  • 5
    So that's great for USD currency, but what about non 100th based currencies, such as BitCoins which have up to 8 decimal places. What about fractional cents (US Gubment tax)?
    – Alan
    Mar 14, 2014 at 22:36
  • 1
    @Alan: Oh please like anyone cares about BitCoins. If you need sub-penny precision, divide by another ten. It's not rocket science. Mar 15, 2014 at 1:41
  • 1
    so much despise in this thread, what's wrong with you people ? how do you deal with division and percentages with integer-cents ? Jan 28, 2019 at 16:20
7

Instead of using integers (which have their own problems)

I would use the bignumber.js library

1
  • 1
    Nice. This is what I was looking for. Looks like it didn't exist when I originally asked the question, but there it is now.
    – Jeff Davis
    Mar 2, 2015 at 19:24
2

There is Math

The Math object is build into the JavaScript spec so every browser has it natively.

As for data types, JavaScript has Number. That's it. We have no other number data type. The best think to do is to try and work with Integers.

1
  • 1
    number is a floating point type and is a poor choice for currencies due to inherent lack of precision and accuracy in certain value ranges
    – RaidenF
    May 17, 2018 at 13:33
2

currency.js or decimal.js should do what you need.

As the names imply, they are designed to handle similar things but decimal.js has many more methods to handle much more than currency, hence the size difference:

  • currency.js - 2.8k (1.3k gzipped)
  • decimal.js - 31.9k (12.7k gzipped)
1

ku4jQuery-kernel contains both a money class and a math utility that contain operations and rounding, including round, roundUp and roundDown. These are nice methods because you can pass a value to round to. For example you can do $.math.round(3.4567, -2) and it will round the number 3.4567 to the nearest 10^-2. The same goes for money. $.money(100.87).divide(2).roundUp().toString() will yield "$50.44". You can go further and add the denomination of money as a second parameter, say "B" for Bitcoin, $.money(100.87, "B").divide(2).roundUp().toString(). You can find more about this library here ku4jQuery-kernel and more libraries that you may find useful here kodmunki github. These libraries are closely maintained and used in many production projects. If you decide to try them, I hope that you find them useful! Happy coding :{)}

1

New kid on the block: moneysafe. It's open-source, and uses a functional approach that allows smart composition.

$(.1) + $(.2) === $(.3).cents;

https://github.com/ericelliott/moneysafe

0

The toFixed method can round to a given number of decimals.

There is also a Javascript sprintf implementation.

0

There are many libraries to help using currency in javascript,typescript.

BIGNUMBER.js
It seems the best library, 1,4M of active users, last publish 7 days ago, only 7 open issues, 33 contributors, 6.3k stars.

https://github.com/MikeMcl/bignumber.js

Node
npm install bignumber.js

Browser

<script src='path/to/bignumber.js'></script>  

Get a minified version from a CDN:

<script src='https://cdn.jsdelivr.net/npm/[email protected]/bignumber.min.js'></script>

Nodejs Common Module:
const BigNumber = require('bignumber.js');

ES Module:
import BigNumber from "bignumber.js";

import { BigNumber } from "./node_modules/bignumber.js/bignumber.mjs";

Usage:

let x = new BigNumber(123.4567);
let y = BigNumber('123456.7e-3');
x.isEqualTo(y) && y.isEqualTo(z);      // true

new BigNumber(0.7 + 0.1)               // '0.7999999999999999'

let x = new BigNumber('1111222233334444555566');
x.toString();                          // "1.111222233334444555566e+21"
x.toFixed();                           // "1111222233334444555566"

x = new BigNumber(255.5)
x.toExponential(5)                  // "2.55500e+2"
x.toFixed(5)                        // "255.50000"
x.toPrecision(5)                    // "255.50"
x.toNumber()                        //  255.5

y = new BigNumber('1234567.898765')
y.toFormat(2)                       // "1,234,567.90"

BigNumber.set({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 })
x = new BigNumber(2)
y = new BigNumber(3)
z = x.dividedBy(y)                        // "0.6666666667"
z.squareRoot()                            // "0.8164965809"
z.exponentiatedBy(-3)                     // "3.3749999995"
z.toString(2)                             // "0.1010101011"
z.multipliedBy(z)                         // "0.44444444448888888889"
z.multipliedBy(z).decimalPlaces(10)       // "0.4444444445"

Other libraries:

https://github.com/royNiladri/js-big-decimal
https://github.com/ericelliott/moneysafe
https://currency.js.org/
https://mikemcl.github.io/decimal.js/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.