php - 负数转换为负数
问题描述
<?php
function convertToHoursMins($total, $format = '%02d:%02d') {
$hours = intval($total / 60);
$minutes = ($total % 60);
return sprintf($format, $hours, $minutes);
}
echo convertToHoursMins($total, $format = '%02d:%02d');
?>
当 $total 为正时,此解决方案非常有效(与许多其他解决方案一样)。另一方面,当 $total 为负数时,$hours 和 $minutes 都会像 -hours:-minutes 一样为负数。我尝试过的每个解决方案都会回显相同的输出,我感到很沮丧。我真的很木感谢一些帮助!
解决方案
一种解决方案是使用的绝对值$total
并-
在需要时添加:
function convertToHoursMins($total, $format = '%02d:%02d')
{
$absTotal = abs($total);
$hours = intval($absTotal / 60);
$minutes = ($absTotal % 60);
return sprintf((0 <= $total ? '' : '-') . $format, $hours, $minutes);
}
推荐阅读
- node.js - 获取邮递员发送的二进制文件数据?
- windows - Impossible to connect a windows mongodb container when --auth is enabled
- excel - 使用 VBA 的 CSV 中的不同或唯一值
- android - 未找到 FBGraphRequestModule 和 Utility AccessToken 构造函数的 react-native-fbsdk 错误
- arrays - Ruby 将嵌套数组字段转换为嵌套 JSON 对象
- java - 在 Appium - Eclipse 中找不到主要活动(具有第 3 方工具抽屉菜单)元素
- python - Pandas COUNTIF 每个数据框列值
- android - 旧 Android API 上的 Apple Style AlertDialog
- python - 如何调整我的 plt.axhline 位置?
- php - Wordpress(PHP):页面未找到标题但内容存在