php 元转分的错误示范
说明
一旦进行金额的互相转化,就非常容易发生错误。所以写个文章记录下来。
错误主要的原因就是内部是浮点数变量。
有兴趣的同学可以试试。
错误的示范。
$price=20.08;
echo yuan_to_fen($price);
function yuan_to_fen($price)
{
return intval(100 * $price);
}
function yuan_to_fen2($price)
{
return floor(100 * $price);
}
function yuan_to_fen3($price)
{
return (int)(100 * $price);
}
正确的示范
$price=20.08;
echo yuan_to_fen($price);
function yuan_to_fen($price)
{
return round(100 * $price);
}
汇总
<?php
$a = 20.08;
$b = yuan_to_fen1($a);
$c = yuan_to_fen2($a);
$d = yuan_to_fen3($a);
$e = yuan_to_fen4($a);
$x = yuan_to_fen31($a);
$y = yuan_to_fen32($a);
$z = yuan_to_fen33($a);
echo('价格=' . $b . "\n");//2007
echo('价格2=' . $c . "\n");//2007
echo('价格3=' . $d . "\n");//2007
echo('价格4=' . $e . "\n");//2008
echo('方法31=' . $x . "\n");//2008
echo('方法32=' . $y . "\n");//2008
echo('方法33=' . $z . "\n");//2008
function yuan_to_fen1($price)
{
return intval(100 * $price);
}
function yuan_to_fen2($price)
{
return floor(100 * $price);
}
function yuan_to_fen3($price)
{
return (int)(100 * $price);
}
function yuan_to_fen4($price)
{
return 100 * $price;
}
function yuan_to_fen31($price)
{
return intval(strval(100 * $price));
}
function yuan_to_fen32($price)
{
//返回浮点数。
return round(100 * $price);
}
function yuan_to_fen33($price)
{
//返回整型,比较推荐这种。
return intval(round(100 * $price));
}
本文出至:学新通技术网
本站名称:
学新通技术网
版权声明:本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
联系方式:luke.wu@swvq.com
标签: