53 lines
1.6 KiB
TypeScript
53 lines
1.6 KiB
TypeScript
import { format as dfFormat } from "date-fns";
|
||
import { de } from "date-fns/locale";
|
||
|
||
export const eur = new Intl.NumberFormat("de-DE", {
|
||
style: "currency",
|
||
currency: "EUR",
|
||
});
|
||
|
||
export const pct = new Intl.NumberFormat("de-DE", {
|
||
style: "percent",
|
||
minimumFractionDigits: 1,
|
||
maximumFractionDigits: 1,
|
||
});
|
||
|
||
export function formatDate(date: Date | string | undefined): string {
|
||
if (!date) return "–";
|
||
const d = typeof date === "string" ? new Date(date) : date;
|
||
return dfFormat(d, "dd.MM.yyyy", { locale: de });
|
||
}
|
||
|
||
export function formatMonth(monthKey: string | undefined): string {
|
||
if (!monthKey) return "–";
|
||
const [year, month] = monthKey.split("-");
|
||
return `${month}.${year}`;
|
||
}
|
||
|
||
export function formatAmount(amount: number): string {
|
||
if (amount === 0) return eur.format(0);
|
||
return eur.format(amount);
|
||
}
|
||
|
||
export function formatEurCompact(value: number): string {
|
||
const abs = Math.abs(value);
|
||
const sign = value < 0 ? "-" : "";
|
||
const suffix = (n: number, digits = 1) =>
|
||
`${sign}${n.toFixed(digits).replace(".", ",")}`;
|
||
if (abs >= 1_000_000) return `${suffix(abs / 1_000_000)} Mio. €`;
|
||
if (abs >= 10_000) return `${suffix(abs / 1000)}k €`;
|
||
if (abs >= 1000) return `${suffix(abs / 1000, 2)}k €`;
|
||
return eur.format(value);
|
||
}
|
||
|
||
export function amountClass(amount: number): string {
|
||
if (amount < 0) return "text-red-600 dark:text-red-400";
|
||
if (amount > 0) return "text-emerald-600 dark:text-emerald-400";
|
||
return "";
|
||
}
|
||
|
||
export function dashIfZero(value: number, formatter: (n: number) => string = (n) => String(n)): string {
|
||
if (value === 0) return "–";
|
||
return formatter(value);
|
||
}
|