Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Money.fromDecimal is subject to floating point calculation errors #1

Closed
anujbiyani opened this issue Aug 21, 2018 · 6 comments
Closed
Assignees
Labels

Comments

@anujbiyani
Copy link

anujbiyani commented Aug 21, 2018

These lines are subject to floating point errors:

let precisionMultiplier = Math.pow(10, currency.decimal_digits)
let resultAmount = amount * precisionMultiplier

For example:
image

The result of this calculation is assumed to be an integer:

if (!isInt(amount))
    throw new TypeError('Amount must be an integer')

but because of floating point calculation inaccuracies that's not always the case.

It's easy to workaround this issue by passing a rounder to Math.fromDecimal, but I feel like this issue is better fixed by ts-money itself, e.g. by using a default rounder.

Would you be open to a PR to address this?

@macor161
Copy link
Owner

Hi @anujbiyani
Thank you very much for submitting this issue. I will create a patch this week.

@macor161 macor161 self-assigned this Aug 26, 2018
@macor161 macor161 added the bug label Aug 26, 2018
@anujbiyani
Copy link
Author

In case it helps, here's the rounder function I'm using:

export function roundTo(n: number, digits: number = 0): number {
  let negative = false;

  if (n < 0) {
    negative = true;
    n = n * -1;
  }

  const multiplicator = Math.pow(10, digits);

  n = parseFloat((n * multiplicator).toFixed(11));
  n = +(Math.round(n) / multiplicator).toFixed(digits);

  if (negative) {
    n = +(n * -1).toFixed(digits);
  }

  return n;
}

It's a Typescript version of https://stackoverflow.com/questions/15762768/javascript-math-round-to-two-decimal-places/15762794#15762794

@macor161
Copy link
Owner

Terribly sorry for the delay, I've been really busy lately. An update will be plublished by monday.
Also, a new version of the library using native BigInt is currently in the making.

@anujbiyani
Copy link
Author

No worries, thanks for the update! Let me know if I can help.

@macor161
Copy link
Owner

@anujbiyani The issue should be fixed now. Basically, we now always use the rounder function in fromDecimal. If no rounder is provided, Math.round is used by default.

Here is the commit

Let me know if you think another approach would be better suited to fix this problem.

Thanks again for signaling the issue, really appreciated! :)

@anujbiyani
Copy link
Author

Looks great! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants