openexchangerates / money.js

money.js is a tiny (1kb) javascript currency conversion library, for web & nodeJS
http://openexchangerates.github.io/money.js
MIT License
1.46k stars 127 forks source link

Rounding Issue #9

Open GutHib opened 11 years ago

GutHib commented 11 years ago

Seems like converting 100 units of one currency to itself will not always result in 100 units. Example:

fx.base = "USD"; fx.rates = { "EUR" : 1.745101, }

Result: Converting 100 EUR to EUR will actually result in 99.9999999999.

Is this something that will be fixed in the library, or do I need to figure out how to do it in my script? (I'm afraid I'm not exactly a js buff, hence the question.)

Thanks!

minopret commented 11 years ago

Unless you employ something like String or github.com/dtrebbien/BigDecimal.js instead of a JavaScript number (IEEE 754 double-precision, 64 bits in total with 52 bits (=13 hex digits) for fractional part of the value), you'll have round-off. In particular when you want one cent and JavaScript stores the amount as 0.01 = (+2^-7)(1+(47ae147ae147ae1 base 16)/(16^15 - 1)), you're really storing the approximation (+2^-7)(1+(47ae147ae147a base 16)/16^13) = 0.0099999999999999984734433411404097569175064563751220703125

GutHib commented 11 years ago

Thanks for the explanation. I'm now rounding the results in javascript (easy enough, even for me ;).