尽管显式铸造,但奇怪的浮点结果行为

时间:2012-10-25 00:05:14

标签: php variables floating-point double decimal

我一整天都遇到过这个问题而且我认为这需要一些帮助。

PHP

$hour1 = (float) $date1 / 10000;
$hour1 = (float) floor($hour1);

$hour2 = (float) $date2 / 10000;
$hour2 = (float) floor($hour2);

$minute1 = (float) $date1 / 10000;
$minute1 = (float) $minute1 - floor($minute1);
$minute1 = (float) $minute1 / 60;
$minute1 = (float) $minute1 * 100;

$minute2 = (float) $date2 / 10000;
$minute2 = (float) $minute2 - floor($minute2);
$minute2 = (float) $minute2 / 60;
$minute2 = (float) $minute2 * 100;

$date = (float) ($hour1 + minute1) - ($hour2 + minute2);
$date = floatval($date);

正如你所看到的那样,我对类型转换有点过分了。

变量值

$minute1 = .564478
$hour1 = 19

$minute2 = .9885546
$hour2 = 8

$date = (float) ($hour1 + minute1) - ($hour2 + minute2);

IS

$date = (float) (19 + .564478) - (8 + .9885546);

现在给出的结果实际上是

11

AND NOT

10.575932......

奇怪的是,当我这样做而没有变量echo (19 + .564478) - (8 + .9885546);时......我得到了10.575932......的浮点结果。

据我所知,大多数编程语言都是浮点数,但我已尝试过所有内容,包括明确输入类型。这是怎么回事?

1 个答案:

答案 0 :(得分:1)

$date = (float) ($hour1 + minute1) - ($hour2 + minute2);

你没有忘记minute1minute2之前的$?

如果你有,那么PHP会将此变量视为常数并仅计算$hour1 - $hour2在你的情况下返回11

应该看起来像

$date = (float) ($hour1 + $minute1) - ($hour2 + $minute2);