Javascript : les nombres
Publié le :
Introduction
Javascript est un langage de programmation qui permet de manipuler des nombres de manière efficace. Cependant, il peut être difficile de formater ces nombres pour les afficher correctement dans une application. Dans cet article, nous allons explorer différentes manières de formater les nombres en Javascript.
Formater les nombres avec Intl
L’API Intl permet de formater les nombres en fonction de la locale de l’utilisateur. Cela signifie que vous pouvez afficher les nombres dans le format approprié pour chaque pays. Voici quelques exemples de formatage de nombres en utilisant l’API Intl.
const number = 1234567.89;
standard decimal
console.log(new Intl.NumberFormat('fr-FR').format(number)); // 1 234 567,89
currency
console.log(
new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(
number,
),
); // 1 234 567,89 €
percent
console.log(
new Intl.NumberFormat('fr-FR', { style: 'percent' }).format(number),
); // 123 456 789 %
percent with decimal
console.log(
new Intl.NumberFormat('fr-FR', {
style: 'percent',
minimumFractionDigits: 2,
}).format(number),
); // 123 456 789,89 %
compact
console.log(
new Intl.NumberFormat('fr-FR', { notation: 'compact' }).format(number),
); // 1,2 M
compact with decimal
console.log(
new Intl.NumberFormat('fr-FR', {
notation: 'compact',
minimumFractionDigits: 2,
}).format(number),
); // 1,23 M
compact and short
console.log(
new Intl.NumberFormat('fr-FR', {
notation: 'compact',
compactDisplay: 'short',
}).format(number),
); // 1,2 M
console.log(
new Intl.NumberFormat('fr-FR', {
notation: 'compact',
compactDisplay: 'short',
}).format(1200),
); // 1,2 k
compact and long
console.log(
new Intl.NumberFormat('fr-FR', {
notation: 'compact',
compactDisplay: 'long',
}).format(number),
); // 1,2 million
console.log(
new Intl.NumberFormat('fr-FR', {
notation: 'compact',
compactDisplay: 'long',
}).format(1200),
); // 1,2 millier
console.log(
new Intl.NumberFormat('fr-FR', {
notation: 'compact',
compactDisplay: 'long',
}).format(12000000000),
); // 12 milliards
ordinal
console.log(
new Intl.NumberFormat('fr-FR', { style: 'ordinal' }).format(number),
); // 1 234 567
scientific
console.log(
new Intl.NumberFormat('fr-FR', { style: 'scientific' }).format(number),
); // 1,23456789E+6
scientific with decimal
console.log(
new Intl.NumberFormat('fr-FR', {
style: 'scientific',
minimumFractionDigits: 2,
}).format(number),
); // 1,23E+6
Engineering
console.log(
new Intl.NumberFormat('fr-FR', { notation: 'engineering' }).format(number),
); // 1,234 M
Engineering with decimal
console.log(
new Intl.NumberFormat('fr-FR', {
notation: 'engineering',
minimumFractionDigits: 2,
}).format(number),
); // 1,23 M Tous les articles de Javascript