Last active
August 29, 2015 14:16
-
-
Save mbunge/13e5f61f0842167c3dad to your computer and use it in GitHub Desktop.
Formatting numbers in Javascript with correct rounding. Binding as Prototype to number.
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
//Plain method | |
var numberFormat = function (number, decPlaces, decSeparator, thouSeparator) { | |
decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces; | |
decSeparator = decSeparator == undefined ? "." : decSeparator; | |
thouSeparator = thouSeparator == undefined ? "," : thouSeparator; | |
var roundAndReduceDecimals = function (num, length) { | |
return Math.round(num * Math.pow(10, length)) / Math.pow(10, length); | |
}; | |
var format = function(n, decPlaces, decSeparator, thouSeparator){ | |
var sign = n < 0 ? "-" : "", | |
i = parseInt(n) + "", | |
j = (j = i.length) > 3 ? j % 3 : 0; | |
return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : ""); | |
}; | |
return format(roundAndReduceDecimals(number, decPlaces), decPlaces, decSeparator, thouSeparator); | |
}; | |
//prototyping to Number object | |
Number.prototype.formatNumber = function(decPlaces, decSeparator, thouSeparator){ | |
return numberFormat(this, decPlaces, decSeparator, thouSeparator); | |
}; | |
//example: | |
var n = 198.6859; | |
n.formatNumber(2, ',', '.'); | |
//n = 198,69 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment