[英]php - add comma thousands separator but remove trailing zeros
我正在嘗試使用PHP將數字格式化為
刪除所有尾隨零
為千位分隔符添加逗號
列出兩個小數點(假定它們不為零)
我嘗試了這個,但是它並沒有完全實現我想要達到的目的:
$prices[$title]['reg_price'] = (float)number_format($membership->sell_price, 2, ".", "");
$prices[$title]['three_year_price'] = (float)number_format($membership->attributes[$aid]->options[$three_year_oid]->price, 2, ".", "");
我發現可以通過將數字強制轉換為浮點數來去除尾隨零。 但是,我發現我需要告訴number_format不要使用千位逗號分隔符,因為否則,將1,500.00強制轉換為浮點數時,結果為1。
因此,總而言之,我希望我的代碼將1500.00更改為1,500,將150.00更改為150,然后將19.99更改為19.99。 我怎樣才能做到這一點?
function parseCurrency($value) {
if ( intval($value) == $value ) {
$return = number_format($value, 0, ".", ",");
}
else {
$return = number_format($value, 2, ".", ",");
/*
If you don't want to remove trailing zeros from decimals,
eg. 19.90 to become: 19.9, remove the next line
*/
$return = rtrim($return, 0);
}
return $return;
}
$prices[] = parseCurrency(1500.00);
$prices[] = parseCurrency(1500.10);
$prices[] = parseCurrency(1500.1);
$prices[] = parseCurrency(1500);
$prices[] = parseCurrency(123.53);
$prices[] = parseCurrency(1224323.53);
$prices[] = parseCurrency(19.99);
print_r($prices);
輸出:
Array
(
[0] => 1,500
[1] => 1,500.1
[2] => 1,500.1
[3] => 1,500
[4] => 123.53
[5] => 1,224,323.53
[6] => 19.99
)
這將插入逗號,四舍五入到小數點后兩位,刪除尾隨零,並刪除尾隨“。”:
rtrim(rtrim(number_format($value,2),0),'.')
您可以使用
ltrim($var, '0');
刪除前導0
。 和
rtirm($var, '0');
到尾隨。
用於替換“。” 為“,”,您可以使用一個函數:
function replace_dot($value) {
$str = str_replace('.', ',', $value);
return $str;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.