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);
CodePudding user response:
toFixed
returns a string, you have to cast it manually.
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));
CodePudding user response:
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);