-
-
Save JamesDullaghan/6720123 to your computer and use it in GitHub Desktop.
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
var PurdyPercent = function (num, options) { | |
this.settings = { | |
hide_decimal_on_whole : true, | |
decimals : 2, | |
truncate : false, // (soon) | |
match_decimals: true, // forces floats to match defined decimal count | |
rounding : 'default', //default, up, down (soon) | |
postfix : '%' | |
}; | |
// helper methods | |
this.extend = function(destination, source) { | |
for (var property in source) { | |
if (source.hasOwnProperty(property)) { | |
destination[property] = source[property]; | |
} | |
} | |
return destination; | |
}; | |
this.is_float = function () { | |
this.modulus = this.num % 1; | |
this.root = parseInt(this.num, 10); | |
return this.modulus % 1 != 0; | |
}; | |
this.set_decimals = function () { | |
var factor = Math.pow(10,this.settings.decimals); | |
this.value = Math.round(this.num*factor)/factor; | |
if (this.settings.match_decimals) this.match_decimals(); | |
}; | |
this.match_decimals = function () { | |
var fraction = this.fraction(), | |
length = fraction.length, | |
diff = this.settings.decimals - length; | |
if (diff > 0) { | |
for (var i = diff - 1; i >= 0; i--) { | |
fraction = fraction + '0'; | |
} | |
} else if (diff < 0) { | |
diff = Math.abs(diff); | |
for (var i = diff - 1; i >= 0; i--) { | |
fraction = fraction.slice(0, -1); | |
} | |
} | |
this.value = [this.root, fraction].join('.'); | |
}; | |
this.fraction = function () { | |
return this.num.toString().split('.')[1]; | |
}; | |
// logic | |
if (num instanceof Array) { | |
this.numerator = parseFloat(num[0]); | |
this.denominator = parseFloat(num[1]); | |
this.num = (this.numerator / this.denominator) * 100.0; | |
} else { | |
this.num = parseFloat(num); | |
} | |
this.extend(this.settings, this.options || options || {}); | |
if (this.is_float()) { | |
this.set_decimals(); | |
} else { | |
if (this.settings.hide_decimal_on_whole) { | |
this.value = parseInt(this.value, 10); | |
} else { | |
this.value = this.num; | |
} | |
} | |
return [this.value, this.settings.postfix].join(''); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment