Ryan
Ryan

Reputation: 127

How can I get MOD in Javascript to return a decimal correctly?

A simple problem I'm working with is taking a time for a 300m run in seconds and converting them to a string so that it reads "9:99.99". To get seconds, I do the following MOD operation:

sec = result % 60;

This doesn't work as expected unless the decimal portion is 0.5 (i.e. 60.5, 75.5, etc.). Any other decimal gives me a result that's off by something that requires 12+ significant digits to express.

For example, 64.55 % 60 gives me 4.5499999999999997 as a result.

I know an easy solution would be to just split on the decimal and concatenate the result with the decimal places, but this just intrigues me. What am I doing wrong, and is there a good way to fix this using MOD alone?

Upvotes: 1

Views: 6086

Answers (1)

jmiraglia
jmiraglia

Reputation: 671

So lets assume you have a value of 921.856 seconds.

var value = 921.856;
var minutes = Math.floor(value/60),  // 15        
    seconds = value % 60,            // 21.856
    time = minutes + ":" + seconds.toFixed(2);  // 15:21.86

To do so without rounding:

time = minutes + ":" + (Math.floor(seconds * 100)/100).toFixed(2); // 15:21.85

Upvotes: 1

Related Questions