sprintf.js - An almost feature complete sprintf implementation
Right below is a copy of the README file which comes right with it.
This library does provide an almost complete reimplementation of the sprintf function known from the standard c library.
The following datatypes are supported:
- A literal percent sign
- A binary number
- An ASCII character represented by the given value
- A signed decimal number
- A floating point value
- An octal number
- A string
- A hexadecimal number (lowercase characters)
- A hexadecimal number (uppercase characters)
All of the usual formatting flags are supported as well. Therefore you may specify the algebraic sign, padding, alignment, width and precision. The syntax is equivalent to the one used by the sprintf c function.
sprintf is registered, ready to be called. Furthermore the String object is extended with a
printf method. Both of these are different means to execute the same functionality.
You may either use the global function
sprintf which returns the newly formatted string if supplied with the format string, as well as all needed arguments:
var formatted = sprintf("The number is %.2f", number);
Or you may use the
printf method directly on the format string:
var formatted = "The number is %.2f".printf(number);
Internally the exactly the same processing takes place. Therefore you may decide freely which syntax you like better.