JavaScript: Intl
22. Jänner 2021
Das Intl-Objekt in JavaScript ist für die Internationalisierung zuständig. Dazu zählen bspw. die Formatierung von einer Nummer oder eines Datums.
Hierfür wird als erstes ein Format-Objekt erstellt, mit welchem anschließend Werte formatiert werden können. Dem Format-Objekt werden die Kultur sowie Formatierungseinstellungen übergeben.
Nachfolgend ein paar der mMn wichtigsten Beispiele:
//Hilfsmethode zur Erstellung eines divs
const append = (value) => {
const el = document.createElement("div");
el.innerText = value;
document.body.appendChild(el);
};
const date = new Date(2000, 9, 7, 23, 35, 10);
const d1 = new Intl.DateTimeFormat("de");
append(d1.format(date)); //7.10.2020
const d2 = new Intl.DateTimeFormat("de", {
weekday: "long"
});
append(d2.format(date)); //Samstag
const d3 = new Intl.DateTimeFormat("de", {
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit"
});
append(d3.format(date)); //07.10.2000, 23:35
const d4 = new Intl.DateTimeFormat("de", {
weekday: "short",
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit"
});
append(d4.format(date)); //Sa., 07.10.2000, 23:35
const num = 123456789.5181;
const n1 = new Intl.NumberFormat("de");
append(n1.format(num)); //123.456.789,518
const n2 = new Intl.NumberFormat("de", {
useGrouping: false
});
append(n2.format(num)); //123456789,518
const n3 = new Intl.NumberFormat("de", {
minimumFractionDigits: 6
});
append(n3.format(num)); //123.456.789,518100
const n4 = new Intl.NumberFormat("de", {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
append(n4.format(num)); //123.456.789,52
const n5 = new Intl.NumberFormat("de", {
maximumSignificantDigits: 2
});
append(n5.format(num)); //120.000.000
const n6 = new Intl.NumberFormat("de", {
style: "currency",
currency: "EUR",
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
append(n6.format(num)); //123.456.789,52 €
const n7 = new Intl.NumberFormat("de", {
style: "percent",
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
append(n7.format(0.8167)); //81,67 %