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
}
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"
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With