Created
July 23, 2011 21:05
-
-
Save manveru/1101879 to your computer and use it in GitHub Desktop.
simple BigDecimal in CoffeeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.