typescriptcurrency-formatting

.toLocaleString() not working to convert number to currency string


I have the following code:

//Incorrectly displays something like "Amount is too low: 3000"
this.statusMessage = "Amount is too low: " + this.inputVals.Amount.toLocaleString('en-US', {
        style: 'currency',
        currency: 'USD',
    })

//Correctly displays something like "Calculated total: $3479.89"
this.statusMessage2 = "Calculated total: " + this.invoiceTotal.toLocaleString('en-US', {
        style: 'currency',
        currency: 'USD',
    })

The currency conversion in this.statusMessage isn't working but the currency conversion in this.statusMessage2 is working without issue. Why would the exact same number.toLocaleString() conversion work in one spot and not the other?

For context, this.inputVals is an object that stores data entered from a form. this.inputVals.Amount is defined as a number. And this.invoiceTotal is calculated by adding some invoice values together.


Solution

  • The issue likely lies not in toLocaleString() itself, but in the actual type or value of this.inputVals.Amount. So Explicitly convert this.inputVals.Amount to a number before formatting.

    this.statusMessage = "Amount is too low: " + Number(this.inputVals.Amount).toLocaleString('en-US', {
        style: 'currency',
        currency: 'USD',
    });