站长资讯网
最全最丰富的资讯网站

一文解析PHP元转分的错误示范(附代码实例)

本篇文章给大家带来了关于php的相关知识,其中主要介绍了通过PHP进行金额(元转分)的互相转化出现的错误,感兴趣的朋友下面一起来看一下吧,希望对大家有帮助。

一文解析PHP元转分的错误示范(附代码实例)

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)); }
登录后复制

推荐学习:《PHP视频教程》

赞(0)
分享到: 更多 (0)