Reputation: 23
I really did not understand how the type assignment system works for variables in typescript. Can anyone help me why this does not work. Thank you
valorParcela:number;
totalCost:number;
VendaProdutoVendaNParcelas: number;
this.valorParcela = Number( this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2);
I expected a simple parseFloat
Upvotes: 2
Views: 2702
Reputation: 36187
toFixed()
returns string. throwing an error because trying to assign to the number type. so just cast to Number(expression)
again or make this variable as string this.valorParcela
this.valorParcela = Number(Number(this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2)));
Upvotes: 0
Reputation: 86790
.toFixed(2);
Always returns string.
And you have assigned type number
.
Upvotes: 1
Reputation: 250206
toFixed
returns a string
which you are assigning to a variable which should be number
. You need another pair of ()
to convert the result of toFixed
back to number
this.valorParcela = Number(( this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2));
Or you can use the unary +
trick to perform number conversion:
this.valorParcela = +(this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2);
Upvotes: 4