JavaScript
Форматирование чисел, дат и валют
Intl вместо самописных форматтеров: локали, валюты, относительное время и множественные формы.
Код
const money = new Intl.NumberFormat('ru-RU', {
style: 'currency', currency: 'RUB', maximumFractionDigits: 0,
});
console.log(money.format(1234567)); // 1 234 567 ₽
const date = new Intl.DateTimeFormat('ru-RU', {
dateStyle: 'long', timeStyle: 'short', timeZone: 'Europe/Moscow',
});
console.log(date.format(new Date()));
// Относительное время: «3 дня назад»
const rtf = new Intl.RelativeTimeFormat('ru-RU', { numeric: 'auto' });
console.log(rtf.format(-3, 'day')); // 3 дня назад
// Размер файла
function formatBytes(bytes) {
if (bytes === 0) return '0 Б';
const units = ['Б', 'КБ', 'МБ', 'ГБ', 'ТБ'];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return `${(bytes / 1024 ** i).toFixed(1)} ${units[i]}`;
}
console.log(formatBytes(5_242_880)); // 5.0 МБ