Page 1 of 1
Problem converting PHP (floor %) code to JavaScript
Posted: Sun Feb 17, 2008 5:18 am
by WaldoMonster
Good working PHP code:
Code: Select all
$seconds = round($miliseconds / 1000);
$hour = floor($seconds / 3600);
$minutes = ($seconds / 60) % 60;
$seconds = $seconds % 60;
JavaScript code where only the seconds are correct:
Code: Select all
var seconds = Math.round(miliseconds / 1000);
var hour = Math.floor(seconds / 3600);
var minutes = (seconds / 60) % 60;
seconds = seconds % 60;
Is the floor different interpreted in Javascript?
Any help would be very welcome.
Re: Problem converting PHP (floor %) code to JavaScript
Posted: Sun Feb 17, 2008 5:20 am
by Benjamin
From what I found it rounds it down..
http://www.w3schools.com/jsref/jsref_floor.asp
What is it doing for you?
Re: Problem converting PHP (floor %) code to JavaScript
Posted: Sun Feb 17, 2008 2:22 pm
by WaldoMonster
Code: Select all
<?php
for ($i = 60; $i < 70; $i++)
{
$seconds = $i;
$hour = floor($seconds / 3600);
$minutes = ($seconds / 60) % 60;
$seconds = $seconds % 60;
echo $hour . ':' . $minutes . ':' . $seconds . '<br>';
}
?>
The php result:
0:1:0
0:1:1
0:1:2
0:1:3
0:1:4
0:1:5
0:1:6
0:1:7
0:1:8
0:1:9
Code: Select all
<script type="text/javascript">
for (var i = 60; i < 70; i++)
{
var seconds = i;
var hour = Math.floor(seconds / 3600);
var minutes = (seconds / 60) % 60;
seconds = seconds % 60;
document.write(hour + ':' + minutes + ':' + seconds + '<br>');
}
</script>
The javascript result:
0:1:0
0:1.0166666666666666:1
0:1.0333333333333334:2
0:1.05:3
0:1.0666666666666666:4
0:1.0833333333333332:5
0:1.1:6
0:1.1166666666666667:7
0:1.1333333333333333:8
0:1.15:9
Re: Problem converting PHP (floor %) code to JavaScript
Posted: Sun Feb 17, 2008 2:39 pm
by Benjamin
Looks like
Code: Select all
var minutes = (seconds / 60) % 60;
needs to be
Code: Select all
var minutes = Math.floor((seconds / 60) % 60);
Re: Problem converting PHP (floor %) code to JavaScript
Posted: Sun Feb 17, 2008 5:08 pm
by WaldoMonster
Thanks for the help astions.
What I now read from
http://en.wikipedia.org/wiki/Modulo_operation is that most languages require integers for modulo.
That this would be a better solution:
Code: Select all
var minutes = Math.floor(seconds / 60) % 60;
Re: Problem converting PHP (floor %) code to JavaScript
Posted: Sun Feb 17, 2008 5:14 pm
by Benjamin
Looks good.