Last active
February 5, 2018 16:05
-
-
Save jiggzson/638f221cff6767c8c97b92d2465322b3 to your computer and use it in GitHub Desktop.
A wrapper to deal with floating point numbers in JavaScript. It does a rough conversion to a fraction and then does the operation. The toDecimal method returns the number back as a decimal. For larger numbers use a bigNumber library
This file contains 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
function F(d) { | |
if(!(this instanceof F)) | |
return new F(d); | |
if(Array.isArray(d)) | |
this.fraction = d; | |
else | |
this.fraction = this.convert(d); | |
} | |
F.prototype.convert = function(d) { | |
var p = d.toString().split('.'); | |
var n = p[1]; | |
//if there's no decimal part then we're done | |
if(!n) | |
return [d, 1]; | |
var k = Math.pow(10, n.length); | |
//return the scaled version | |
return [Math.floor(k*d), k]; | |
}; | |
F.prototype.add = function(f) { | |
if(!this.isF(f)) | |
f = new F(f); | |
return new F([f.fraction[1]*this.fraction[0]+this.fraction[1]*f.fraction[0], | |
this.fraction[1]*f.fraction[1]]); | |
}; | |
//Alias | |
F.prototype.plus = F.prototype.add; | |
F.prototype.subtract = function(f) { | |
if(!this.isF(f)) | |
f = new F(f); | |
return new F([f.fraction[1]*this.fraction[0]-this.fraction[1]*f.fraction[0], | |
this.fraction[1]*f.fraction[1]]); | |
}; | |
//Alias | |
F.prototype.minus = F.prototype.subtract; | |
F.prototype.multiply = function(f) { | |
if(!this.isF(f)) | |
f = new F(f); | |
return new F([this.fraction[0]*f.fraction[0], this.fraction[1]*f.fraction[1]]); | |
}; | |
//Alias | |
F.prototype.times = F.prototype.multiply; | |
F.prototype.divide = function(f) { | |
if(!this.isF(f)) | |
f = new F(f); | |
return new F([this.fraction[0]*f.fraction[1], this.fraction[1]*f.fraction[0]]); | |
}; | |
//Alias | |
F.prototype.over = F.prototype.divide; | |
F.prototype.isF = function(f) { | |
return f instanceof F; | |
}; | |
F.prototype.toDecimal = function() { | |
return this.fraction[0]/this.fraction[1]; | |
}; | |
F.prototype.valueOf = function() { | |
return this.toDecimal(); | |
}; | |
F.prototype.toString = function() { | |
return String(this.toDecimal()); | |
}; | |
//Example: | |
//var x = new F(0.2).plus(0.1).times(2); | |
//console.log(x.toDecimal()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment