Home > Mobile >  How to custom NumberFormat currency?
How to custom NumberFormat currency?

Time:11-22

I'm using JS Intl.NumberFormat() to format Thai Currency like this:

const number = 123456789;
const object = {
  style: 'currency',
  currency: 'THB',
  currencyDisplay: 'name',
  trailingZeroDisplay: 'stripIfInteger'
}

console.log(new Intl.NumberFormat('th-TH', object).format(number)); 
// => "123,456,789 บาทไทย"

console.log(new Intl.NumberFormat('en-EN', object).format(number)); 
//=> "123,456,789 Thai baht"

However, for Thai Locale, I want it return "123,456,789 บาท" and "123,456,789 Baht" for English. How can I do that?

CodePudding user response:

I think that one of the useful solutions is to set a function that changes the ends of the formatted number, I have created one for you:

    const number = 123456789;
    const object = {
      style: "currency",
      currency: "THB",
      currencyDisplay: "name",
      trailingZeroDisplay: "stripIfInteger",
    };

    // Function that returns formatted number
    const formatNumberFunction = (local, object, number) => {
          const formatedNumberValue = Intl.NumberFormat(local, object).format(number);

      //   Return the value according to the ends of the formatedNumberValue
      if (formatedNumberValue.endsWith("บาทไทย")) {
        return formatedNumberValue.slice(0, -3);
      }

      return formatedNumberValue.slice(0, -5);
    };

    console.log(formatNumberFunction("th-TH", object, number));
    console.log(formatNumberFunction("en-EN", object, number));

The output is:

    123,456,789 บาท
    123,456,789 Thai
  • Related