Is multiplying currencies possible in JavaScript?

I keep getting a NaN response every time I try. This is the console log operation:

a="$100"

b=a*2
NaN

Hey, you can multiply integer by integer, not string by an integer as in your code.

@ayanda you can’t multiply numbers together if they are represented as strings. So both a="100" and a="$100" would fail in this instance, as they are both defined as strings. a=100 would succeed, as it is defined as a number.

By default your JavaScript code doesn’t know what dollars are, so you’d need to add some meta data to your code to express this. For example you could store your values in objects, like this:

let order1 =  {
  amount: '100',
  currency: 'dollars',
  symbol: '$'
}

You can then access the amount to do calculations like this — order1.amount, manipulate it, and then print the amount with currency symbol with 'order.symbol + order1.amount'

Or even better, you could provide the formatted output using the JavaScript Intl API, which is a bit more complex to learn, but is a properly designed tool built into the browser for handling just these kinds of problems. Have a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat

1 Like

I’d thought there was a method I could of used… ah well. Thanks Chris!! :slight_smile:

and oof Intl.NumberFormat() is incredible. Thanks for introducing me to it :smiley: