Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
number.round
String.prototype.lpad = function (padding, length) {
var string = this;
while (string.length < length) {
string = padding + string;
}
return string;
}
Number.prototype.round = function(base) {
if (base == null || base < 0) {
return this;
}
var string = this.toString();
var point_index = string.indexOf(".");
if (point_index == -1) {
return this;
}
var symbol_index = point_index + 1 + base;
if (symbol_index >= string.length) {
return this;
}
var integer = parseInt(string.substring(0, point_index), 10);
var fractional = parseInt(string.substring(point_index + 1, point_index + 1 + base), 10) || 0;
var max_fractional = Math.pow(10, base);
var symbol = parseInt(string.charAt(symbol_index), 10);
if (symbol >= 5) {
if (base == 0) {
integer ++;
} else {
if (fractional + 1 == max_fractional) {
integer ++;
fractional = 0;
} else {
fractional ++;
}
}
}
return new Number(parseFloat(integer + "." + (fractional.toString().lpad("0", base))));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment