Skip to content

Commit

Permalink
Parentheses for negative values. Related d3#5.
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock committed Jun 17, 2015
1 parent 1e30118 commit e49b6cf
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 3 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ The *sign* can be:

* `-` - nothing for positive and a minus sign for negative. (Default behavior.)
* `+` - a plus sign for positive and a minus sign for negative.
* `(` - nothing for positive and parentheses for negative.
* ` ` (space) - a space for positive and a minus sign for negative.

The *symbol* can be:
Expand Down
2 changes: 1 addition & 1 deletion src/formatSpecifier.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import formatTypes from "./formatTypes";

// [[fill]align][sign][symbol][0][width][,][.precision][type]
var re = /^(?:(.)?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?([a-z%])?$/i;
var re = /^(?:(.)?([<>=^]))?([+\-\( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?([a-z%])?$/i;

export default function(specifier) {
return new FormatSpecifier(specifier);
Expand Down
5 changes: 3 additions & 2 deletions src/localeFormat.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,14 @@ export default function(locale) {

// Convert negative to positive, and compute the prefix.
// Note that -0 is not less than 0, but 1 / -0 is!
var valuePrefix = (value < 0 || 1 / value < 0 ? (value *= -1, "-") : sign === "-" ? "" : sign) + prefix;
var valueNegative = (value < 0 || 1 / value < 0) && (value *= -1, true),
valuePrefix = (valueNegative ? (sign === "(" ? sign : "-") : sign === "-" || sign === "(" ? "" : sign) + prefix;

// Perform the initial formatting.
value = formatType(value, precision);

// Compute the suffix.
var valueSuffix = suffix + (type === "s" ? prefixes[8 + prefixExponent / 3] : "");
var valueSuffix = suffix + (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + (valueNegative && sign === "(" ? ")" : "");

// Break the formatted value into the integer “value” part that can be
// grouped, and fractional or exponential “suffix” part that is not.
Expand Down
12 changes: 12 additions & 0 deletions test/format-type-none-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,15 @@ tape("format(\"$\") can output a currency", function(test) {
test.equal(f(-4.2), "-$4.2");
test.end();
});

tape("format(\"($\") can output a currency with parentheses for negative values", function(test) {
var f = format.format("($");
test.equal(f(0), "$0");
test.equal(f(.042), "$0.042");
test.equal(f(.42), "$0.42");
test.equal(f(4.2), "$4.2");
test.equal(f(-.042), "($0.042)");
test.equal(f(-.42), "($0.42)");
test.equal(f(-4.2), "($4.2)");
test.end();
});

0 comments on commit e49b6cf

Please sign in to comment.