如何将浮点数转换为整数


How to convert float to whole number?

我有一个数字存储在mysql类型float。根据我所读到的,我应该能够通过使用floor()来转换浮点数,但是尝试这个或其他任何东西都不起作用。希望有人能指出我做错了什么?

例子. .

数据库显示价格为$25.00 -在我的php页面中,我有以下代码(将价格行转换为$price后):

$price2 = floor($price);
echo $price;
echo '<br>';
echo $price2;

我的结果打印:

$25.00
0

我也试过用'round'代替'floor'。相同的结果。

这是因为您使用$25.00作为输入,而$使PHP认为您正在尝试将字符串四舍五入—PHP将(非数字)字符串四舍五入为0。

  • floor =四舍五入
  • ceil =四舍五入
  • round =他们在文法学校教你的相同的过程

但是如果字符串中有$,这些都不起作用。我建议你做一些类似'$' . round( str_replace( '$', '', $price ) * 100 ) / 100的事情。(乘法和除法使其四舍五入到最接近的便士(而不是美元),str_replace使其处理的是数值,然后加上$。如果你真的很花哨,那就跟随下面的

$dollar = '$' . round( str_replace( '$', '', $price ) * 100 ) / 100;
// the following makes sure that there are two places to the right of the decimal
$pieces = explode( '.', $dollar );
if( isset($pieces[1]) && strlen( $pieces[1] ) == 1 )
{
    $pieces[1].='0';
    $dollar = implode('.', $pieces);
}
// if you like, you can also make it so that if !pieces[1] add the pennies in

正如cwallenpoole所说,您不能四舍五入非数值。但是,您可以将其改为数字,例如

$price = '$25.25';
echo sprintf('$%0.2f', floor(preg_replace('/[^'d'.]/', null, $price)));