From 2d75b68a4169eaef4768d174975af7b1dac0dbd3 Mon Sep 17 00:00:00 2001 From: ashwalk33r Date: Sat, 4 Apr 2020 14:28:09 +0200 Subject: [PATCH] change regex matching precision in order to reflect C documentation: if the period is specified without an explicit value for precision, 0 is assumed --- src/sprintf.js | 6 +++++- test/test.js | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/sprintf.js b/src/sprintf.js index 65d6324..5dc4cb5 100644 --- a/src/sprintf.js +++ b/src/sprintf.js @@ -14,7 +14,7 @@ not_json: /[^j]/, text: /^[^\x25]+/, modulo: /^\x25{2}/, - placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d*))?([b-gijostTuvxX])/, key: /^([a-z_][a-z_\d]*)/i, key_access: /^\.([a-z_][a-z_\d]*)/i, index_access: /^\[(\d+)\]/, @@ -184,6 +184,10 @@ throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported') } + if (typeof match[7] === 'string' && match[7].length === 0) { + match[7] = '0'; + } + parse_tree.push( { placeholder: match[0], diff --git a/test/test.js b/test/test.js index 9588da6..cf38c2b 100644 --- a/test/test.js +++ b/test/test.js @@ -109,4 +109,16 @@ describe('sprintfjs', function() { it('should return formated strings for callbacks', function() { assert.equal('foobar', sprintf('%s', function() { return 'foobar' })) }) + + it('should respect precision', function() { + assert.equal('1.200', sprintf("%.3f", 1.2)) // input shorter then required precision - fill in + assert.equal('1', sprintf("%.f", 1.2)) + + assert.equal(sprintf("%.0f", 1.123), sprintf("%.f", 1.456)) // use 0 as precision if not given + + assert.equal('1.123', sprintf("%.3f", 1.1231)) // input overflows given precision - round down + assert.equal('1', sprintf("%.f", 1.1231)) + assert.equal('1.124', sprintf("%.3f", 1.1239)) // input overflows given precision - round up + assert.equal('2', sprintf("%.f", 1.9)) + }) })