Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions src/sprintf.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
return sprintf.format.call(null, cache[key], arguments)
}

sprintf.formatNumber = function(val) {
return val.toString()
}

sprintf.format = function(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = ''
for (i = 0; i < tree_length; i++) {
Expand Down Expand Up @@ -122,12 +126,13 @@
output[output.length] = arg
}
else {
if (re.number.test(match[8]) && (!is_positive || match[3])) {
sign = is_positive ? '+' : '-'
arg = arg.toString().replace(re.sign, '')
}
else {
sign = ''
sign = ''
if (re.number.test(match[8])) {
arg = sprintf.formatNumber(arg)
if (!is_positive || match[3]) {
sign = is_positive ? '+' : '-'
arg = arg.replace(re.sign, '')
}
}
pad_character = match[4] ? match[4] === '0' ? '0' : match[4].charAt(1) : ' '
pad_length = match[6] - (sign + arg).length
Expand Down
5 changes: 5 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,9 @@ describe("sprintfjs", function() {
assert.equal("foobar", sprintf("%s", function() { return "foobar" }))
assert.equal(Date.now(), sprintf("%s", Date.now)) // should pass...
})

it("should support custom number formatting", function(){
sprintf.formatNumber = function(val) { return val.toString() + ".00"; };
assert.equal("123.00", sprintf("%d", 123));
})
})