Formatting in percent by Intl.NumberFormat in JavaScript

Viewed 21726
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%

2 Answers

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"
};
Related