Live data from Hacker News

How to Handle Monetary Values in JavaScript

frontstuff.io

1–10 of 115 posts

Re: How to Handle Monetary Values in JavaScript

#3

I looked into using Dinero.js before but it was overkill for my use case of calculating cart totals in USD only. I went with Big.js because it was better suited for what I wanted: a small library for decimal arithmetic.

Can you illustrate a case where you can't use regular FP arithmetic and round to 2 decimal places at the end?

Re: How to Handle Monetary Values in JavaScript

#5
post #3

I looked into using Dinero.js before but it was overkill for my use case of calculating cart totals in USD only. I went with Big.js because it was better suited for what I wanted: a small library for decimal arithmetic.

Can you illustrate a case where you can't use regular FP arithmetic and round to 2 decimal places at the end?

You can't model 1.0 correctly but it will be something like 1.000006667. If you add enough of these numbers you will be off.

Re: How to Handle Monetary Values in JavaScript

#6
post #4

I really like the approach Perl 6 takes with FatRat[1]. You basically have an object which holds a numerator and denominator, so all arithmetic calculations do not loose precision. [1] https://docs.perl6.org/type/FatRat

Ever seen the numeric tower of lisp? https://en.wikipedia.org/wiki/Numerical_tower

The link to the scheme documentation that goes over this is quite good.

Re: How to Handle Monetary Values in JavaScript

#8
post #6
post #4

I really like the approach Perl 6 takes with FatRat[1]. You basically have an object which holds a numerator and denominator, so all arithmetic calculations do not loose precision. [1] https://docs.perl6.org/type/FatRat

Ever seen the numeric tower of lisp? https://en.wikipedia.org/wiki/Numerical_tower The link to the scheme documentation that goes over this is quite good.

That's fantastic! Do you have any more resources on this? I'd like to look at that concept in more depth.

Re: How to Handle Monetary Values in JavaScript

#9
post #3

I looked into using Dinero.js before but it was overkill for my use case of calculating cart totals in USD only. I went with Big.js because it was better suited for what I wanted: a small library for decimal arithmetic.

Can you illustrate a case where you can't use regular FP arithmetic and round to 2 decimal places at the end?

  (1.005).toFixed(2) // Expected rounding to "1.01"
  "1.00"

Re: How to Handle Monetary Values in JavaScript

#10
post #5
post #3

Earlier quoted context omitted.

Can you illustrate a case where you can't use regular FP arithmetic and round to 2 decimal places at the end?

You can't model 1.0 correctly but it will be something like 1.000006667. If you add enough of these numbers you will be off.

Your details are off. 1.0 is precisely representable in double precision floating point with no error.
Post reply on HN