Sandra Schlichting
Sandra Schlichting

Reputation: 26026

Possible to save type in object?

The below example gives the correct calculation, but for some reason p.calcPrice is a string. I would expect that it is a number, as .toFixed() doesn't make sense in a string.

Whenever I use p.calcPrice, do I then have to cast it with +p.calcPrice, or can I have TypeScript treat as a number, so I don't have to cast it?

p.calcPrice = (
  price *
  +p.amount *
  (1 - pD / 100) *
  (1 - mD / 100)
).toFixed(2);

Upvotes: 1

Views: 65

Answers (2)

Amir Ghezelbash
Amir Ghezelbash

Reputation: 2415

toFixed returns a string, you have to cast it manually.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed#return_value

one way for casting would be to wrap it in Number:

p.calcPrice = Number((price * +p.amount * (1 - pD / 100) * (1 - mD / 100)).toFixed(2));

Upvotes: 1

Dezzley
Dezzley

Reputation: 1835

You could rewrite it like this so it will already be cast to a number because toFixed returns a string. Mind the + before the clause.:

p.calcPrice = +(
  price *
  +p.amount *
  (1 - pD / 100) *
  (1 - mD / 100)
).toFixed(2);

Upvotes: 1

Related Questions