将float转换为整数时,php出错

时间:2017-07-21 16:50:32

标签: php

当我从一个浮点数转换为整数时,它表现得很奇怪并且没有预期的结果

<?php
$amount = str_replace(",", "", '1,051.36') * 100; //105136
$number = (int)$amount; //105135

2 个答案:

答案 0 :(得分:1)

您可以使用 round(),floor() ceil()函数将浮动金额舍入到最接近的整数。

// round to next highest Int 
$number_ceiled = ceil($amount); //105136

// round to next lowest Int 
$number_floored = floor($amount); //105135

// can do both and round to the much closed 
$number_rounded = round($amount); //105136

return (int)$number_rounded; //105136

在你的情况下考虑特别是round()。

以下是文档:

http://php.net/manual/en/function.round.php

http://php.net/manual/en/function.ceil.php

php.net/manual/en/function.floor.php

干杯,

答案 1 :(得分:0)

你可以这样:

{{1}}