Skip to content
Advertisement

Deprecated: Implicit conversion from float to int loses precision

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.

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement