本篇文章給大家?guī)砹岁P(guān)于php的相關(guān)知識(shí),其中主要介紹了通過PHP進(jìn)行金額(元轉(zhuǎn)分)的互相轉(zhuǎn)化出現(xiàn)的錯(cuò)誤,感興趣的朋友下面一起來看一下吧,希望對(duì)大家有幫助。
php 元轉(zhuǎn)分的錯(cuò)誤示范
說明
一旦進(jìn)行金額的互相轉(zhuǎn)化,就非常容易發(fā)生錯(cuò)誤。所以寫個(gè)文章記錄下來。
錯(cuò)誤主要的原因就是內(nèi)部是浮點(diǎn)數(shù)變量。
有興趣的同學(xué)可以試試。
錯(cuò)誤的示范。
$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); }
登錄后復(fù)制
正確的示范
$price=20.08; echo yuan_to_fen($price); function yuan_to_fen($price) { return round(100 * $price); }
登錄后復(fù)制
匯總
<?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('價(jià)格=' . $b . "n");//2007 echo('價(jià)格2=' . $c . "n");//2007 echo('價(jià)格3=' . $d . "n");//2007 echo('價(jià)格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) { //返回浮點(diǎn)數(shù)。 return round(100 * $price); } function yuan_to_fen33($price) { //返回整型,比較推薦這種。 return intval(round(100 * $price)); }
登錄后復(fù)制
推薦學(xué)習(xí):《PHP視頻教程》