PHP 类型转换 float->int

2021-12-31 00:00:00 types casting php

鉴于此 PHP 代码:

Given this PHP code:

// total is 71.24 (float)
$value = $total * 100;
var_dump($value);
$valuecast = (int)$value;
var_dump($valuecast);
settype($value, 'int');
var_dump($value);

var_dump($value) 给出 float(7124)

var_dump($value) gives float(7124)

var_dump($valuecast) 给出 int(7123)

var_dump($valuecast) gives int(7123)

var_dump($value) 后 settype 给出 int(7123)

var_dump($value) after settype gives int(7123)

如何获得正确的类型转换?

How can I get the correct type conversion?

推荐答案

对于 float 到 int,我建议 round.这是为了迎合 IEEE 浮点不精确.

For float to int, I'd suggest round. This is to cater to IEEE float imprecision.

相关文章