If you don’t have the luxury of a such an implementation you have a couple of options. The first is to operate in cents. Do all your calculations in cents treating monetary amounts as integers. You must be careful however to avoid performing calcs that could result in a fractional result. Doing so would force the JS runtime to coerce the value into a floating point data type. The other option is to create a basic BigDecimal implementation yourself. Just create a wrapper type which stores both sides of the decimal point as an integer. Similar to treating everything as cents, simply provide a set of methods (an API) that allow you to operate on the number without having to think about how to manipulate the separate parts of the number.

]]>You ask if 0.1 + 0.2 – 0.3 < 0.00001 (or some other suitably small number). This works for all real-world cases. It isn’t that big a deal. Please do not flame me with complaints that it increases download size.

]]>Is it insane to try to evaluate mathematical expressions as late as possible? 1/10 + 2/10 === 3/10, 1/3 + 1/5 === 5/15 + 3/15 === 8/15, etc. The parser could figure out that 0.1 should be represented as 1/10 and then 0.1 + 0.2 === 0.3.

]]>Something like (I hope this formats right):

`var sanePrice = function() {`

` var rawPrice = 0;`

` this.__defineGetter__("price", function() {`

` return Math.round( (rawPrice * 1000000)) / 1000000;`

` });`

` this.__defineSetter__("price", function(fpPrice) {`

` if(typeof fpPrice == "number") {`

` rawPrice = fpPrice;`

` }`

` else {`

` throw new Error("Price must be a number")`

` }`

` });`

` this.__defineGetter__("fpPrice", function() { return rawPrice });`

`}`

`var p = new sanePrice();`

`p.price = (0.1 * 0.2);`

`console.log(p.price) // returns 0.02`

`console.log(p.fpPrice) // returns 0.020000000000000004`

While I love BCD, I’ve rarely had it available to me (Atari BASIC did BCD). I hate the idea of adding a new type.

]]>