Skip to content

Commit

Permalink
Fix #42 - round-to-zero test.
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock committed Feb 28, 2017
1 parent b7e1c02 commit 28e6d1d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 21 deletions.
23 changes: 4 additions & 19 deletions src/locale.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,27 +58,12 @@ export default function(locale) {
} else {
value = +value;

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

// Perform the initial formatting.
value = formatType(value, precision);
var valueNegative = value < 0;
value = formatType(Math.abs(value), precision);

// If the original value was negative, it may be rounded to zero during
// formatting; treat this as (positive) zero.
if (valueNegative) {
i = -1, n = value.length;
valueNegative = false;
while (++i < n) {
if (c = value.charCodeAt(i), (48 < c && c < 58)
|| (type === "x" && 96 < c && c < 103)
|| (type === "X" && 64 < c && c < 71)) {
valueNegative = true;
break;
}
}
}
// If a negative value rounds to zero during formatting, treat as positive.
if (valueNegative && +value === 0) valueNegative = false;

// Compute the prefix and suffix.
valuePrefix = (valueNegative ? (sign === "(" ? sign : "-") : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
Expand Down
9 changes: 7 additions & 2 deletions test/format-type-f-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,13 @@ tape("format(\"f\") can display integers in fixed-point notation", function(test
});

tape("format(\"f\") can format negative zero as zero", function(test) {
test.equal(format.format("1f")(-0), "0.000000");
test.equal(format.format("1f")(-1e-12), "0.000000");
test.equal(format.format("f")(-0), "0.000000");
test.equal(format.format("f")(-1e-12), "0.000000");
test.end();
});

tape("format(\"f\") can format negative infinity", function(test) {
test.equal(format.format("f")(-Infinity), "-Infinity");
test.end();
});

Expand Down
10 changes: 10 additions & 0 deletions test/format-type-none-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,13 @@ tape("format(\"($\") can output a currency with parentheses for negative values"
test.equal(f(-4.2), "($4.2)");
test.end();
});

tape("format(\"\") can format negative zero as zero", function(test) {
test.equal(format.format("")(-0), "0");
test.end();
});

tape("format(\"\") can format negative infinity", function(test) {
test.equal(format.format("")(-Infinity), "-Infinity");
test.end();
});

0 comments on commit 28e6d1d

Please sign in to comment.