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视频教程》
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号