Files
Battle-for-Tismo/shared/text_format.js
T
2026-09-17 22:01:30 +02:00

54 lines
1.5 KiB
JavaScript

// Small formatting helpers shared by the UI, ported from
// scripts/classes/text_format.gd.
export function groupDigits(value) {
const truncated = Math.trunc(value);
const digits = String(Math.abs(truncated));
let grouped = "";
let count = 0;
for (let i = digits.length - 1; i >= 0; i--) {
grouped = digits[i] + grouped;
count += 1;
if (count % 3 === 0 && i > 0) grouped = " " + grouped;
}
return (truncated < 0 ? "-" : "") + grouped;
}
function threeSignificant(value) {
const digits = Math.floor(Math.log(value) / Math.log(10)) + 1;
const decimals = Math.max(0, 3 - digits);
const factor = Math.pow(10, decimals);
const rounded = Math.round(value * factor) / factor;
let text = rounded.toFixed(decimals);
if (text.includes(".")) text = text.replace(/0+$/, "").replace(/\.$/, "");
return text;
}
export function compact(value) {
if (Math.abs(value) < 1e-9) return "0";
const sign = value < 0 ? "-" : "";
let amount = Math.abs(value);
const suffixes = ["", "K", "M", "B", "T"];
let index = 0;
while (amount >= 1000 && index < suffixes.length - 1) {
amount /= 1000;
index += 1;
}
let text = threeSignificant(amount);
if (text === "1000" && index < suffixes.length - 1) {
index += 1;
text = "1";
}
return sign + text + suffixes[index];
}
export function improvements(list) {
if (!list || list.length === 0) return "None";
return list.join(", ");
}
export function hours(value) {
if (value < 1.0) return value.toFixed(2) + " h";
return value.toFixed(1) + " h";
}