Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting in percent by Intl.NumberFormat in JavaScript

Tags:

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%

like image 343
Clary Avatar asked Jul 07 '17 19:07

Clary


2 Answers

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%";.

like image 75
Patrick Evans Avatar answered Dec 02 '22 23:12

Patrick Evans


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"
};
like image 40
Ashif Zafar Avatar answered Dec 02 '22 21:12

Ashif Zafar