Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions src/tickFormat.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import {tickStep} from "d3-array";
import {format, formatPrefix, formatSpecifier, precisionFixed, precisionPrefix, precisionRound} from "d3-format";

export default function tickFormat(start, stop, count, specifier) {
export default function tickFormat(start, stop, count, specifierIn) {
var step = tickStep(start, stop, count),
precision;
specifier = formatSpecifier(specifier == null ? ",f" : specifier);
const specifier = formatSpecifier(specifierIn == null ? ",f" : specifierIn);
switch (specifier.type) {
case "s": {
var value = Math.max(Math.abs(start), Math.abs(stop));
Expand All @@ -21,7 +21,14 @@ export default function tickFormat(start, stop, count, specifier) {
}
case "f":
case "%": {
if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === "%") * 2;
if (specifier.precision == null) {
if (step === 0) {
if (specifierIn == null) specifier.trim = true;
}
else if (!isNaN(precision = precisionFixed(step))) {
specifier.precision = precision - (specifier.type === "%") * 2;
}
}
break;
}
}
Expand Down
15 changes: 15 additions & 0 deletions test/tickFormat-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,19 @@ it("tickFormat(start, stop, count) uses the default precision when the domain is
const f = tickFormat(0, NaN, 10);
assert.strictEqual(f + "", " >-,f");
assert.strictEqual(f(0.12), "0.120000");

const f2 = tickFormat(0.12, NaN, 10);
assert.strictEqual(f2 + "", " >-,f");
assert.strictEqual(f2(0.12), "0.120000");
});

it("tickFormat(start, stop, count) uses the default precision with trimming when the domain is collapsed", () => {
const f = tickFormat(5.5, 5.5, 10);
assert.strictEqual(f + "", " >-,~f");
assert.strictEqual(f(0), "0");
assert.strictEqual(f(5.5), "5.5");
assert.strictEqual(f(Math.PI), "3.141593");
assert.strictEqual(f(-Math.PI), "−3.141593");
assert.strictEqual(f(Math.PI * 1e7), "31,415,926.535898");
assert.strictEqual(f(-Math.PI * 1e7), "−31,415,926.535898");
});