Created
June 8, 2011 04:38
-
-
Save mahonnaise/1013780 to your computer and use it in GitHub Desktop.
sprintf utility function
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
var sprintf = function (text) { | |
var i = 1, args = arguments; | |
return text.replace(/%(0)?(\d*)?\.?(\d*)?(s|f)/g, function (pattern) { | |
var a = arguments, | |
precision = +a[3], | |
value = args[i++], | |
padSize = +a[2] - (~~value).toString().length, | |
padding = padSize > 0 ? (new Array(padSize + 1).join(a[1] || ' ')) : ''; | |
return padding + (a[4] === 'f' && a[3] ? value.toFixed(+precision) : value); | |
}); | |
}; | |
console.log('[' + sprintf("%5.2f", Math.PI) + ']'); | |
//[ 3.14] | |
console.log('[' + sprintf("%.6f", Math.PI) + ']'); | |
//[3.141593] | |
console.log('[' + sprintf("%5f", Math.PI) + ']'); | |
//[ 3.141592653589793] | |
console.log('[' + sprintf("%5.0f", Math.PI) + ']'); | |
//[ 3] | |
console.log('[' + sprintf("%5f", -Math.PI) + ']'); | |
//[ -3.141592653589793] | |
console.log('[' + sprintf("%5f", 33.9) + ']'); | |
//[ 33.9] | |
console.log('[' + sprintf("%05f", 33.9) + ']'); | |
//[00033.9] | |
console.log(sprintf('i got %f problems but %s aint one', 99, 'string formatting')); | |
//i got 99 problems but string formatting aint one |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment