Skip to content

Instantly share code, notes, and snippets.

@mahonnaise
Created June 8, 2011 04:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahonnaise/1013780 to your computer and use it in GitHub Desktop.
Save mahonnaise/1013780 to your computer and use it in GitHub Desktop.
sprintf utility function
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