本篇文章給大家帶來了關于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視頻教程》
站長資訊網