JavaScript math problems

I'm working on a program that uses a PC and a mobile device to make model trains (yes, like toy trains) behave like a real train, and I'm having an issue with my physics engine. When it decelerates, the deceleration never quite hits exactly 0, it just perpetually bounces from negative to positive decimals. Is there a good way to prevent this?

This might be a little inefficient, but before you decrease your vector magnitude, you could add a check that looks if the deceleration minus the magnitude of the vector flips the sign, and if so, assign the magnitude to 0.

if (this.vx - < 0) this.vx = 0; // 'this' is train object

If you're doing it how I think you're doing it, then the deceleration subtracts the magnitude on both sides of the sign? The problem would be that you're deceleration constant is larger than the actual speed of the train, so it flips back and forth between the two numbers. This solution might cause more problems than it fixes, though, depending on how it's implemented. Can you show some code that includes all the relevant variables and how they were implemented?

Also, are you doing this in a browser? Have you tried using the debugging tools that come in a standard modern browser? You can do step-by-step to find the exact code that's causing the bug, and see if there are any logic issues there.

How small are the values, it could be just due to machine precision.

Thank you, that helped a lot! I ended up with this, which forces it to cross zero every time it changes from negative to positive. That fixed it!

if (speedMPH > 0) { //if speed is positive right now,
     if (newSpeed < 0) { //and it's about to flip to negative
         newSpeed = 0 //make sure it crosses exactly 0 once
         console.log("Forcing zero crossing")
 else if (speedMPH < 0) {
     if (newSpeed > 0) {
         newSpeed = 0
         console.log("Forcing zero crossing")

For reference, speedMPH is the current speed, newSpeed is set as the speed by a function further in the program, then the cycle repeats. If you're interested in the final product I'm keeping it at , anyway thanks for the help!