0

I would need to find a way to calculate the price of a product multiplied by the quantity requested, but I would have to use the comma instead of the period, and the return value must be numeric.

There is a better way to do it than this code.

Can you give me a hand?

function getPrice(price,quantity){
return (parseFloat(price.replace(',','.'))*quantity).toFixed(2).toString().replace(".", ",")
}

console.log(getPrice("4,9",3))
Paul
  • 3,644
  • 9
  • 47
  • 113
  • `toFixed()` returns a string, so there's no need for `.toString()` after that. Also, you seem pretty sure there's a better way of doing it. What does "better" mean to you? Because to me, if it works, it ships. – Heretic Monkey Jan 12 '21 at 16:30
  • I don't know your use case but I think a more efficient way could be using period in the background for calculations and using comma only for views. – Abdullah Akçam Jan 12 '21 at 16:33
  • you can also look at [Number.prototype.toLocaleString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) for locale based number display – pilchard Jan 12 '21 at 16:36
  • Does this answer your question? [How to format numbers as currency string?](https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-string) – Heretic Monkey Jan 12 '21 at 16:36

0 Answers0