Skip to content

Commit a6b2c2a

Browse files
committed
Fix adjustFormat dropping d3-format specs that start with a sign flag
A d3-format specifier beginning with a sign flag (+, -, (, space) was silently ignored: adjustFormat prepended a trim tilde to the whole string, producing an invalid spec like ~+.2f. d3.format then threw, numberFormat fell back to noFormat, and the raw unformatted number was shown (e.g. %{y:+.2f} rendered 12.3456789 instead of +12.35). Skip past an optional leading sign flag and symbol ($, #) before the trim heuristic and reattach it, so the tilde is only added in a valid position. Formats without such a prefix are unaffected. Fixes #7897
1 parent 227bba9 commit a6b2c2a

2 files changed

Lines changed: 15 additions & 2 deletions

File tree

src/lib/index.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,15 @@ lib.adjustFormat = function adjustFormat(formatStr) {
1919
if (/^\d%/.test(formatStr)) return '~%';
2020
if (/^\ds/.test(formatStr)) return '~s';
2121

22-
// try adding tilde to the start of format in order to trim
23-
if (!/^[~,.0$]/.test(formatStr) && /[&fps]/.test(formatStr)) return '~' + formatStr;
22+
// A d3-format spec may begin with a sign flag (+, -, (, space) and/or a
23+
// symbol ($, #). Look past that prefix before deciding whether to trim, and
24+
// reattach it: prepending the tilde to the whole string (e.g. "~+.2f") is an
25+
// invalid spec that d3Format rejects, so "+.2f" used to be silently dropped.
26+
var prefix = (formatStr.match(/^[+\-( ]?[$#]?/) || [''])[0];
27+
var rest = formatStr.slice(prefix.length);
28+
29+
// try adding tilde to trim trailing zeros
30+
if (!/^[~,.0$]/.test(rest) && /[&fps]/.test(rest)) return prefix + '~' + rest;
2431

2532
return formatStr;
2633
};

test/jasmine/tests/lib_number_format_test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,12 @@ describe('number format', function() {
5353
{ format: '0f', number: float, exp: '12345.678901'},
5454
{ format: '1f', number: float, exp: '12345.678901'},
5555

56+
// sign flag with an explicit precision must not be dropped (was silently
57+
// ignored because adjustFormat produced the invalid spec "~+.2f")
58+
{ format: '+.2f', number: float, exp: '+12345.68'},
59+
{ format: '+.0f', number: float, exp: '+12346'},
60+
{ format: '-.4f', number: float, exp: '12345.6789'},
61+
5662
// space-filled and default sign
5763
{ format: '-13', number: float, exp: '-12345.678901'},
5864
{ format: '-14', number: float, exp: ' -12345.678901'},

0 commit comments

Comments
 (0)