Javascript Math.cos and Math.sin are inaccurate. Is there any solution?
It's very, very close to zero, though. (~ 10^-16)
And alert(Math.sin(Math.PI/2))
does return 1
.
It's just one of things you have to be careful of when dealing with floating point arithmetic. Rounding errors pop up all over the place.
you can use
Math.sin(Math.PI).toFixed(3) // "0.000"
Examples:
const cos = (a) => Math.cos(Math.PI * a / 180);
cos(90) // 6.123233995736766e-17
then you can use .toFixed()
cos(90).toFixed(3) // "0.000"
Note
.toFixed()
returns string, so you can parse it to float using parseFloat()
parseFloat(cos(90).toFixed(3)) // 0.000