Formatting in percent by Intl.NumberFormat in JavaScript
var discount = 25.1;
var option = {
style: 'percent',
maximumFractionDigits: 2
};
var formatter = new Intl.NumberFormat(locale, option);
var discountFormat = formatter.format(discount );
// discountFormat return -> 2.510%
While I want you to come back like this: 25.10%
Because 25.1
is 2510%
. Percentages are fractions of 100
. If you had 100% it would be 100/100
which is equal to 1. So 25.1%
is 25/100
or 0.251
not 25.1
var discount = 0.251;
var option = {
style: 'percent',
minimumFractionDigits: 2,
maximumFractionDigits: 2
};
var formatter = new Intl.NumberFormat("en-US",option);
var discountFormat = formatter.format(discount );
console.log(discountFormat);
Also if you wanted to keep the trailing zero you would need to set minimumFractionDigits
as the default for percentages is 0.
If your value is the actual percentage to be displayed, you would just put the % symbol on the end, eg value = 25.1+"0%";
.
or you can use Arrow function
const percentageFormatter = intl = value => intl.formateNumber(value/100, {
style: "percent",
maximumFractionDigits:2
}
if you want to use for field as a percentage field with “%” suffix.
or else
const Num = 3223;
const CurrencyFormatter = intl => intl.formateNumber(intl.locale, {
style: "percent",
maximumFractionDigits:2
}
console.log(CurrencyFormatter (Num));
If you wan to use the locale for the currency symbol you can make use of {toLocaleString}
export const currencyFormatWithLocale = (value, locale) => {
const currency = currencyToLocale[locale];
return (
!!value &&
value.toLocaleString(`${locale}`, {
style: "currency",
currency: currency
})
);
};
/* To be updated based on need - French - Canada and US locale handled */
export const currencyToLocale = {
"fr-CA": "CAD",
"hi-IND": "INR",
"en-US": "USD"
};
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .