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));
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 6

花里胡哨,BC函数帮你搞定

1年前 评论
yyy123456 (楼主) 1年前
Imuyu (作者) 1年前
<?php

$a = 0;
while($a< 7000000){
  $b = intval(''.(20.08*100));
  // $b = (int)''.(20.08*100);
  //$b = intval(round(20.08*100));
  $a = $a+1;
}

你猜哪个速度最快呢?

1年前 评论
yyy123456 (楼主) 1年前
JinBB (作者) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
51
粉丝
7
喜欢
60
收藏
94
排名:591
访问:1.3 万
私信
所有博文
社区赞助商