format_ops — Number Formatting
tsb provides a suite of number-formatting helpers that mirror pandas'
style.format() and Series.map() patterns.
Every function is zero-dependency and fully typed.
| Function | Example input | Example output | Notes |
|---|---|---|---|
formatFloat(n, d) | 3.14159, 2 | "3.14" | Fixed decimal places |
formatPercent(n, d) | 0.1234, 1 | "12.3%" | Multiplies by 100 |
formatScientific(n, d) | 12345.678, 3 | "1.235e+4" | Exponential notation |
formatEngineering(n, d) | 12345.678, 3 | "12.346e+3" | Exponent multiple of 3 |
formatThousands(n, d, sep) | 1234567.89, 2 | "1,234,567.89" | Thousands separator |
formatCurrency(n, sym, d) | 1234.5, "$" | "$1,234.50" | Currency prefix + thousands |
formatCompact(n, d) | 1_234_567, 2 | "1.23M" | K / M / B / T suffixes |
import {
makeFloatFormatter,
makePercentFormatter,
makeCurrencyFormatter,
} from "tsb";
const fmtFloat = makeFloatFormatter(3); // (v) => formatFloat(v, 3)
const fmtPct = makePercentFormatter(1); // (v) => formatPercent(v, 1)
const fmtDollar = makeCurrencyFormatter("$"); // (v) => formatCurrency(v, "$", 2)
fmtFloat(3.14159); // "3.142"
fmtPct(0.0825); // "8.3%"
fmtDollar(9999.99); // "$9,999.99"
import { Series, applySeriesFormatter, makePercentFormatter } from "tsb";
const returns = new Series({ data: [0.05, -0.02, 0.134, 0.007], name: "returns" });
const formatted = applySeriesFormatter(returns, makePercentFormatter(1));
// Series<string> ["5.0%", "-2.0%", "13.4%", "0.7%"]
import { DataFrame, applyDataFrameFormatter, makeCurrencyFormatter, makePercentFormatter } from "tsb";
const df = DataFrame.fromColumns({
price: [1_299.99, 899.50, 45.00],
change: [0.025, -0.031, 0.102],
volume: [15_000, 8_200, 230_000],
});
const formatted = applyDataFrameFormatter(df, {
price: makeCurrencyFormatter("$", 2),
change: makePercentFormatter(2),
});
// formatted = {
// price: ["$1,299.99", "$899.50", "$45.00"],
// change: ["2.50%", "-3.10%", "10.20%"],
// volume: ["15000", "8200", "230000"], // no formatter → String(v)
// }
import { Series, DataFrame, seriesToString, dataFrameToString, makeFloatFormatter } from "tsb";
const s = new Series({ data: [1.2, 3.4, 5.6], name: "value" });
console.log(seriesToString(s, { formatter: makeFloatFormatter(1) }));
// 0 1.2
// 1 3.4
// 2 5.6
// Name: value, dtype: float64
const df = DataFrame.fromColumns({ a: [1, 2, 3], b: [4.0, 5.0, 6.0] });
console.log(dataFrameToString(df));
// a b
// 0 1 4.0
// 1 2 5.0
// 2 3 6.0