Yoran Cobben - 4 months ago 52

TypeScript Question

`distanceX = ((this.frontclickedX - originX) / originX).toFixed(2);`

distanceY = (-(this.frontclickedY - originY) / originY).toFixed(2);

let distanceZ: number = (-(this.frontclickedY - originY) / originY).toFixed(2);

my browser throws an error when I calculated distanceZ:

`Type 'string' is not assignable to type 'number'.`

the first two lines work perfectly, but the third doesn't really work.

As you can see it is even exact the same calculation as distanceY. I tried to parseFloat() it first. But then it starts to complain that I can only parse a string to a float, and that I didn't provide one.

I'm quite confused at the moment, so some help or a solution would be much appreciated!

Thanks in advance!

Edit: I tried to simplify my code.

Made the distances private and added setters and getters.

`private _distanceX: number;`

private _distanceY: number;

private _distanceZ: number;

get distanceZ(): number {

return this._distanceZ;

}

set distanceZ(value: number) {

this._distanceZ = value;

} ...

calculateBadgeDistance(): void{

this.distanceX = (5.001).toFixed(2);

this.distanceY = (5.001).toFixed(2);

this.distanceZ = (5.001).toFixed(2);

}

Now I got the error on all 3 lines.

Answer

The method `toFixed()`

converts a number to a string.
You have to parse the variables to numbers:

```
let distanceZ:number = parseFloat((-(this.frontclickedY - originY) / originY).toFixed(2));
```

Alternatively temporary store the string, and parse it later

```
let distanceZTxt:string = (-(this.frontclickedY - originY) / originY).toFixed(2);
let distanceZ:number = parseFloat(distanceZTxt);
```