Search code examples
typescriptdeno

Convert toUSD(amount) function to prototype function. How?


I have the following function that works fine.

function toUSD(amount): string {
  // RETURN number in $0.00 format
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD"
  }).format(amount);
};

I use it like this:

console.log(toUSD(123)); // output = $123.00

What would I need to change to use it like this?

console.log((123).toUSD()); // output = $123.00

Solution

  • Your function should not use input parameters to pass the value. You have to refer to the current number using this:

    function toUSD(this: number): string {
      return new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD"
      }).format(this);
    };
    

    Then you can assign it to Number.prototype as also suggested by Ximaz' answer:

    Number.prototype.toUSD = toUSD;
    

    After that, you can call it like (123).toUSD() which outputs $123.00.