Home > database >  Deprecated: Implicit conversion from float to int loses precision
Deprecated: Implicit conversion from float to int loses precision

Time:09-09

I am playing around with getting hours and minutes out of seconds, and we all see the many many questions that are similar to this, but I am not sure what solution is the best

$seconds = 6530;

$secs = $seconds % 60;
$hrs = $seconds / 60;
$mins = $hrs % 60; // Causing the issue
$hrs = $hrs / 60;

var_dump($hrs, $mins, $secs);

This is the code, which gives me:

Deprecated: Implicit conversion from float 108.83333333333333 to int loses precision 
float(1.8138888888888889)
int(48)
int(50)

I understand the error, thats not the issue, the issue is how to solve it. I have tried

$mins = (int) ($hrs % 60);

and 

$mins = intval($hrs % 60);

as well as

$mins = (int) round($hrs % 60);

But I get the same issue.

Here is the sandbox for reference: https://onlinephp.io/c/b5b45

What is the proper way to solve this? I do want this as an int, but not sure how to properly convert it.

CodePudding user response:

If you want to int your float to int, you can use some function such a floor round etc..

in your case you are looking for floor so you should do:

<?php


$seconds = 6530;

$secs = $seconds % 60;
$hrs = $seconds / 60;
$hrs = floor($hrs);
$mins = $hrs % 60;
$hrs = $hrs / 60;

var_dump($hrs, $mins, $secs);

That's giving:

float(1.8)
int(48)
int(50)

CodePudding user response:

The answer that has been approved here doesn't give the correct result. We know the result should be:

int(1)
int(48)
int(50)

Which is indeed 6530 seconds because: 3600 2880 50 = 6530.

The correct way to compute this is:

$seconds = 6530;

$modulusSeconds = $seconds % 60;
$minutes = intdiv($seconds, 60);
$modulusMinutes = $minutes % 60;
$hours = intdiv($minutes, 60);

var_dump($hours, $modulusMinutes, $modulusSeconds);

See: https://3v4l.org/8JKQ9

There is however another way to compute this:

$seconds = 6530;

echo gmdate("G i s", $seconds);

Which is simpler. This results in:

1 48 50
  •  Tags:  
  • php
  • Related