Public
Edited
Jan 19, 2024
Insert cell
Insert cell
Insert cell
// Take unformatted value and return a formatted one
formatValue = function (value) {
if (value === 0) return 0;

const isNeg = value < 0;
const absValue = Math.abs(value);
const powerOf10 = Math.log10(absValue);
const formattedValue = d3.format(specifierScale(powerOf10))(absValue);

return isNeg ? -formattedValue : formattedValue;
}
Insert cell
Insert cell
// Wich specifier to use based on power of 10
specifierScale = d3.scaleThreshold(
[-2, -1, 0, 1, 3, 4, 5, 6],
// [".2e", ".3", ".3", ".3", ".4", ",.4", ",.5", ",.6", ".2e"]
[".2e", ".3", ".3", ".3", ".2f", ",.4", ",.5", ",.6", ".2e"]
)
Insert cell
Insert cell
// n = 0
// n = 0.00003245
// n = 0.003245
// n = 0.03245
// n = 0.3245
// n = 1.000000000000000120034
// n = 4.324
n = 92.1
// n = 42.356
// n = -42.356
// n = 424.356
// n = 424
// n = 43245.3567
// n = 438245.3567
// n = 4245123.35
// n = 4245123123.355678
Insert cell
formatValue(n)
Insert cell
Insert cell
d3.format(s)(n)
Insert cell
s = specifierScale(Math.log10(n))
Insert cell
Math.log10(n)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more