Skip to content

Instantly share code, notes, and snippets.

@mrsweaters
Last active December 24, 2015 00:39
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mrsweaters/6718220 to your computer and use it in GitHub Desktop.
Make percentages purdy. Whole numbers don't display decimals by default, will force defined decimal length for floats, all customizable.
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
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, options || {});
if (this.is_float()) {
this.set_decimals();
} else {
if (this.settings.hide_decimal_on_whole) {
this.value = parseInt(this.num, 10);
} else {
this.value = this.num;
}
}
return [this.value, this.settings.postfix].join('');
};

Examples:

// pass in integer or floating point.
-> PurdyPercent(27.0)
-> "27%"

// pass in numerator and denominator
-> PurdyPercent([5.424, 28])
-> "19.37%"

// set decimal places to three
-> PurdyPercent(38.43895, {decimals: 3})
-> "38.438%"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment