From 9037c308eb5ab669c17088ffb93192f38b8152ba Mon Sep 17 00:00:00 2001 From: Simon Stamcar Date: Tue, 9 May 2017 20:50:44 +0200 Subject: [PATCH] Add support for custom number formatting --- src/sprintf.js | 17 +++++++++++------ test/test.js | 5 +++++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/sprintf.js b/src/sprintf.js index 2e4df3a..43947d7 100644 --- a/src/sprintf.js +++ b/src/sprintf.js @@ -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++) { @@ -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 diff --git a/test/test.js b/test/test.js index 89c6ba9..bebf331 100644 --- a/test/test.js +++ b/test/test.js @@ -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)); + }) })