[英]PHP - number_format issues
默認情況下, number_format
愚蠢地四舍五入數字。 是否有一種簡單的方法可以關閉舍入? 我正在使用隨機生成的數字,並且可以得到類似...
42533 * .003 = 127.599或,
42533 * .03 = 1275.99或,
42533 * .3 = 12759.9
我需要用number_format(或其他格式)以傳統的美國格式(用逗號分隔千位)來表示結果,而不是四舍五入。
有任何想法嗎?
number_format的第二個參數是數字中的小數位數。 最簡單的發現方法可能是將其視為字符串(根據此問題 )。 傳統的美國格式是默認行為,因此您無需指定其余參數。
$num_decimals = strlen(substr(strrchr($number, "."), 1));
$formatted_number = number_format($number, $num_decimals);
如果有人對此感興趣,我已經寫了一個小函數來解決這個問題。
歸功於以上的Joel Hinz,我想出了...
function number_format_with_decimals($value, $round_to){
//$value is the decimal number you want to show with number_format.
//$round_to is the deicimal place value you want to round to.
$round_to_decimals = strlen(substr(strrchr($value, "."), $round_to));
$ans = number_format($value, $round_to);
return $ans;
}
我嘗試了這些解決方案,但最終的答案是:
$output=money_format('%!i', $value);
這使您像3,234.90而不是3,234或3,234.9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.