Last active
August 29, 2015 14:19
-
-
Save andrew-aladev/3ffaaf689745bc49d2b1 to your computer and use it in GitHub Desktop.
number.round
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
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