Public
Edited
Dec 21, 2022
1 star
Insert cell
Insert cell
format = (f) => d3.format(f > 10 ** 4 ? "d" : f > 1 ? ".5g" : ".4f")(f)
Insert cell
format2 = (f) => d3.format(f > 10 ** 4 ? "d" : ".5g")(f)
Insert cell
format3 = (f) => d3.format(",.5g")(f)
Insert cell
// From https://www.hamiltonulmer.com/just-enough-precision
function justEnoughPrecision(n) {
if (typeof n !== "number") throw Error("argument must be a number");
const str = n.toString();
// if there are no floating point digits, return the string
if (n === ~~n) return str;
const [left, right] = str.split(".");

// count the integer side
const leftSideDigits = left
.split("")
.filter((l) => l !== "-") // remove the negative sign
.join("").length;

// calculate the remaining available precision
const remainingPrecision = Math.max(0, 5 - leftSideDigits);
// take the remaining precision from the floating point side.
const remainingFloatingPoints = right.slice(0, remainingPrecision);
// format a new string
return `${left}${remainingFloatingPoints.length ? "." : ""}${
remainingFloatingPoints || ""
}`;
}
Insert cell
numbers = [
123456789, 12345678.9, 1234567.89, 123456.789, 12345.6789, 1234.56789,
123.456789, 12.3456789, 1.23456789, 0.123456789, 0.0123456789, 0.00123456789,
0.000123456789, 0.0000123456789, 0.00000123456789, 0.000000123456789
]
Insert cell
numbers.map(format)
Insert cell
numbers.map(format2)
Insert cell
numbers.map(format3)
Insert cell
numbers.map(justEnoughPrecision)
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