Public
Edited
Jul 27, 2023
Fork of Untitled
Insert cell
values = [
{
ones: 2.3456,
tens: 23.232,
hundreds: 123.23,
thousands: 2332.43,
mills: 1212243
}
].map((d) => {
Object.keys(d).forEach((k) => (d[k] = formatValue(d[k])));
return d;
})
Insert cell
viewof table = Inputs.table(values)
Insert cell
function formatValue(aVal, aStatInfo = { valPrefix: "$", valSuffix: "" }) {
let aFormattedVal = aStatInfo.valPrefix;

if (aVal >= 1000) {
if (aVal >= 1000000) {
if (aVal / 1000000 === Math.round(aVal / 1000000)) {
aFormattedVal += `${Math.floor(aVal / 1000000)}m`;
} else {
aFormattedVal += `${Math.floor(aVal / 1000000)}.${(
Math.floor(aVal % 1000000) / 100000
).toFixed(0)}m`;
}
} else {
aFormattedVal += `${Math.floor(aVal / 1000)}k`;
}
} else {
aFormattedVal += `${aVal}`;
}

aFormattedVal += aStatInfo.valSuffix;

return aFormattedVal;
}
Insert cell
viewof format = Inputs.select(["999G999G999G990D00", "999G999G999G990", "999G999G999G99D00", "90D0", "9D000", "999D000"], {label: "Select format"})
Insert cell
number = 0.12456789
Insert cell
formatNumber(number, format)
Insert cell
function formatNumber(num, format) {
let result = "";
let numStr = num.toString();
let decimalIndex = numStr.indexOf(".");
let integerPart = decimalIndex !== -1 ? numStr.slice(0, decimalIndex) : numStr;
let decimalPart = decimalIndex !== -1 ? numStr.slice(decimalIndex + 1) : "";
let formatDecimalIndex = format.indexOf("D");
let formatIntegerPart = formatDecimalIndex !== -1 ? format.slice(0, formatDecimalIndex) : format;
let formatDecimalPart = formatDecimalIndex !== -1 ? format.slice(formatDecimalIndex + 1) : "";
let integerGroups = formatIntegerPart.split("G").reverse();
let integerGroupsCount = integerGroups.length;
for (let i = 0; i < integerGroupsCount; i++) {
let group = integerGroups[i];
let groupLength = group.length;
if (integerPart.length >= groupLength) {
result = integerPart.slice(-groupLength) + result;
integerPart = integerPart.slice(0, -groupLength);
} else {
result = integerPart + result;
integerPart = "";
}
if (i < integerGroupsCount - 1 && integerPart.length > 0) {
result = "," + result;
}
}
if (formatIntegerPart[0] === "9" && result === "") {
result = "";
} else if (formatIntegerPart[formatIntegerPart.length-1] === "9" && result === "0") {
result = ".";
} else if (formatDecimalIndex !== -1 || result !== "") {
result += ".";
}
for (let i = 0; i < formatDecimalPart.length; i++) {
if (i < decimalPart.length) {
result += decimalPart[i];
} else if (formatDecimalPart[i] === "0") {
result += "0";
}
}
if(result[result.length-1] === "."){
result = result.slice(0,-1);
}
return result;
}

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