Why does javascript math operations produce different results than python? and how to fix it?
python:
>> 4-((4/3)*3)+1
>> 2
javascript:
>> 4-((4/3)*3)+1
>> 1
Why does javascript math operations produce different results than python? and how to fix it?
python:
>> 4-((4/3)*3)+1
>> 2
javascript:
>> 4-((4/3)*3)+1
>> 1
In python, 4/3 == 1
, since it is an an integer operation. In JS it is a floating point operation, and therefore 4/3 === 1.3333333333333333
.
If you want floating point operations in python, have floating point in the equation. E.g.
4-((4/3)*3)+1 == 2
(Integer)
4-((4.0/3.0)*3)+1 == 1
(Float)
Actually javascript produces decimal values of 1.333333 for 4/3 and it multiplied with 3 which tends to produce 4. 1 is the correct result for 4-((4/3)*3)+1 but if you want 2 as your result then you need to parse the value of 4/3 to int so 1.333333 will become 1 which is multiplied with 3 will produce 3.
alert(4-(parseInt(4/3)*3)+1)