goodeggs / goodeggs-money

Reliable money math with BigNumber wrapped inside Cents
MIT License
3 stars 0 forks source link

Unable to use `dividedBy` when result is a floating point value #5

Open brycefisher opened 7 years ago

brycefisher commented 7 years ago

Repro steps:

$ node
> var Cents = require('goodeggs-money')
undefined
> var tenDollars = new Cents(1000)
undefined
> tenDollars.dividedBy(9)
Error: 111.11111111111111 must be an int
    at new Cents (/Users/bryce/node_modules/goodeggs-money/lib/index.js:67:13)
    at Cents.module.exports.Cents.dividedBy (/Users/bryce/node_modules/goodeggs-money/lib/index.js:131:12)
    at repl:1:12
    at REPLServer.defaultEval (repl.js:252:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:417:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:210:10)

The reason this happens is that after we use BigNumber to perform the division operator, we wrap the resulting value back into a new Cents() object. The constructor for Cents specifically disallows non-integer values, so any division operation that results in a non-integer result will fail.

I was able to work around this issue thusly:

 tenDollars.toBigNumber().dividedBy(9)

EDIT: Also, its possible to lose precision, but not throw, by specifying a transform function like so:

tenDollars.dividedBy(9, transform: 'round')