Skip to content

Instantly share code, notes, and snippets.

@manveru
Created July 23, 2011 21:05
Show Gist options
  • Save manveru/1101879 to your computer and use it in GitHub Desktop.
Save manveru/1101879 to your computer and use it in GitHub Desktop.
simple BigDecimal in CoffeeScript
class BigDecimal
constructor: (number, @precision) ->
@number = @gobble(number)
plus: (other) ->
@bd @number + @gobble(other)
minus: (other) ->
@bd @number - @gobble(other)
div: (other) ->
@bd @number / @gobble(other)
mult: (other) ->
@bd @number * @gobble(other)
toString: ->
@number.toString()
toFixed: (precision) ->
@number.toFixed(precision)
equals: (other) ->
@gobble(other) == @number
gobble: (number) ->
parseFloat(number.toFixed(@precision))
bd: (input) ->
new BigDecimal(@gobble(input), @precision)
a = new BigDecimal(0.1, 2)
b = new BigDecimal(0.2, 2)
c = new BigDecimal(0.3, 2)
console.log(a.plus(b))
console.log(c)
console.log(a.plus(b).equals(c))
@jmstacey
Copy link

Ran across this while doing some BigDecimal research. At cursory glance it looks like this will pseudo handle the precision issue by hiding it, but since it still relies on a float it's still limited to a max number of 2^53.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment