對於大多數美國人來說,我們不希望看到貨幣符號顯示為「USD」,因此「%i」並不適用。以下是我用來獲得大多數人期望看到的數字格式的方法。
$number = 123.4
setlocale(LC_MONETARY, 'en_US.UTF-8');
money_format('%.2n', $number);
輸出
$123.40
這會在開頭顯示一個美元符號,並在結尾顯示兩位數。
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
money_format — 將數字格式化為貨幣字串
此函式自 PHP 7.4.0 起已被標記為 *已棄用*,並自 PHP 8.0.0 起已被 *移除*。強烈建議不要依賴此函式。
money_format() 會傳回格式化後的 number
。這個函式包裝了 C 語言函式庫的 strfmon() 函式,不同之處在於此實作一次只轉換一個數字。
format
格式規格包含以下序列
一個 %
字元
可選旗標
可選欄位寬度
可選左精準度
可選右精準度
一個必要的轉換字元
可以使用以下一個或多個可選旗標
=
f=
字元後接一個(單位元組)字元 f,用作數值填充字元。預設的填充字元是空格。
^
^
+
或 (
!
指定正數和負數的格式樣式。如果使用 +
,則會使用語系設定中對應 +
和 -
的符號。如果使用 (
,則負數會以括號括起來。如果未指定,則預設為 +
。
-
!
-
如果存在,它將使所有欄位靠左對齊(向右填充),與預設的欄位靠右對齊(向左填充)相反。
一個十進位數字字串,指定最小欄位寬度。除非使用 -
旗標,否則欄位將靠右對齊。預設值為 0(零)。
左精準度
#
n
^
旗標抑制分組,則會在新增填充字元(如果有的話)之前插入分組分隔符號。分組分隔符號不會套用於填充字元,即使填充字元是數字。為了確保對齊,格式化輸出中數字前後出現的任何字元(例如貨幣或正負號)會根據需要以空格填充,使其正負格式的長度相等。
.
p
一個句點後接小數點後位數 (p)。如果 p 的值為 0(零),則會省略小數點及其右邊的數字。如果未包含右精準度,則預設值將由目前使用的語系設定決定。格式化的金額在格式化之前會四捨五入到指定的位數。
轉換字元
i
%
數字根據語系設定的國際貨幣格式進行格式化(例如,美國語系設定:USD 1,234.56)。
n
要格式化的數字。
範例 #1 money_format() 範例
我們將使用不同的地區設定和格式規格來說明此函式的用法。
<?php
$number = 1234.56;
// 以 en_US 語系設定印出國際格式
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56
// 義大利國家格式,含小數點後兩位
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// Eu 1.234,56
// 使用負數
$number = -1234.5672;
// 美國國家格式,使用 () 表示負數
// 左邊精度為 10 位數
setlocale(LC_MONETARY, 'en_US');
echo money_format('%(#10n', $number) . "\n";
// ($ 1,234.57)
// 與上述格式相似,加上小數點後兩位
// 並使用 '*' 作為填充字元
echo money_format('%=*(#10.2n', $number) . "\n";
// ($********1,234.57)
// 左對齊,寬度 14 個位置,左邊精度 8 位數
// 右邊精度 2 位數,不使用千分位符號
// 並使用 de_DE 語系設定的國際格式。
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
// Eu 1234,56****
// 在轉換規範前後加上一些文字
setlocale(LC_MONETARY, 'en_GB');
$fmt = 'The final value is %i (after a 10%% discount)';
echo money_format($fmt, 1234.56) . "\n";
// The final value is GBP 1,234.56 (after a 10% discount)
?>
注意:
只有在系統具備 strfmon 功能時,才能定義 money_format() 函式。例如,Windows 並不具備此功能,因此在 Windows 中,money_format() 函式是未定義的。
注意:
地區設定的
LC_MONETARY
類別會影響此函式的行為。在使用此函式之前,請使用 setlocale() 設定適當的預設地區設定。
對於大多數美國人來說,我們不希望看到貨幣符號顯示為「USD」,因此「%i」並不適用。以下是我用來獲得大多數人期望看到的數字格式的方法。
$number = 123.4
setlocale(LC_MONETARY, 'en_US.UTF-8');
money_format('%.2n', $number);
輸出
$123.40
這會在開頭顯示一個美元符號,並在結尾顯示兩位數。
這是一個之前發佈過的函式,不過已經修正了各種錯誤。
感謝 Stuart Roe 回報了列印信號的錯誤。
<?php
/*
That it is an implementation of the function money_format for the
platforms that do not it bear.
The function accepts to same string of format accepts for the
original function of the PHP.
(Sorry. my writing in English is very bad)
The function is tested using PHP 5.1.4 in Windows XP
and Apache WebServer.
*/
function money_format($format, $number)
{
$regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'.
'(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
if (setlocale(LC_MONETARY, 0) == 'C') {
setlocale(LC_MONETARY, '');
}
$locale = localeconv();
preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
foreach ($matches as $fmatch) {
$value = floatval($number);
$flags = array(
'fillchar' => preg_match('/\=(.)/', $fmatch[1], $match) ?
$match[1] : ' ',
'nogroup' => preg_match('/\^/', $fmatch[1]) > 0,
'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
$match[0] : '+',
'nosimbol' => preg_match('/\!/', $fmatch[1]) > 0,
'isleft' => preg_match('/\-/', $fmatch[1]) > 0
);
$width = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
$left = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
$right = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
$conversion = $fmatch[5];
$positive = true;
if ($value < 0) {
$positive = false;
$value *= -1;
}
$letter = $positive ? 'p' : 'n';
$prefix = $suffix = $cprefix = $csuffix = $signal = '';
$signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
switch (true) {
case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
$prefix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
$suffix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
$cprefix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
$csuffix = $signal;
break;
case $flags['usesignal'] == '(':
case $locale["{$letter}_sign_posn"] == 0:
$prefix = '(';
$suffix = ')';
break;
}
if (!$flags['nosimbol']) {
$currency = $cprefix .
($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
$csuffix;
} else {
$currency = '';
}
$space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
$value = number_format($value, $right, $locale['mon_decimal_point'],
$flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
$value = @explode($locale['mon_decimal_point'], $value);
$n = strlen($prefix) + strlen($currency) + strlen($value[0]);
if ($left > 0 && $left > $n) {
$value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
}
$value = implode($locale['mon_decimal_point'], $value);
if ($locale["{$letter}_cs_precedes"]) {
$value = $prefix . $currency . $space . $value . $suffix;
} else {
$value = $prefix . $value . $space . $currency . $suffix;
}
if ($width > 0) {
$value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
STR_PAD_RIGHT : STR_PAD_LEFT);
}
$format = str_replace($fmatch[0], $value, $format);
}
return $format;
}
?>
在我的 Windows XP SP3 執行 PHP 5.4.13 的環境中,Rafael M. Salvioni 的函式 localeconv(); 傳回了一個無效的陣列,因此為了避免出現警告訊息:implode(): Invalid arguments passed,我手動新增了 $locale。對於其他語言,只需使用正確的設定填入陣列即可。
<?
$locale = array(
'decimal_point' => '.',
'thousands_sep' => '',
'int_curr_symbol' => 'EUR',
'currency_symbol' => '€',
'mon_decimal_point' => ',',
'mon_thousands_sep' => '.',
'positive_sign' => '',
'negative_sign' => '-',
'int_frac_digits' => 2,
'frac_digits' => 2,
'p_cs_precedes' => 0,
'p_sep_by_space' => 1,
'p_sign_posn' => 1,
'n_sign_posn' => 1,
'grouping' => array(),
'mon_grouping' => array(0 => 3, 1 => 3)
);
?>
如果 money_format 似乎無法正常運作,請確認您定義了有效的語系。例如,在 Debian 上,「en_US」不是有效的語系 — 您需要「en_US.UTF-8」或「en_US.ISO-8559-1」。
這讓我困擾了一陣子。Debian 在 /usr/share/i18n/SUPPORTED 中有一個有效語系的清單;如果它無法正常運作,請在那裡找到您的語系。
要捨棄零值的小數,請使用以下方法
<?php
/*
與 PHP 的 number_format() 相同,但如果結尾是 .0、.00、.000 等,則完全捨去小數部分。
返回值為字串類型,數值已四捨五入 - 與 PHP 的 number_format() 相同:
範例:
number_format_drop_zero_decimals(54.378, 2) ==> '54.38'
number_format_drop_zero_decimals(54.00, 2) ==> '54'
*/
function number_format_drop_zero_decimals($n, $n_decimals)
{
return ((floor($n) == round($n, $n_decimals)) ? number_format($n) : number_format($n, $n_decimals));
}
?>
結果
number_format_drop_zero_decimals(54.377, 2) ==> 54.38
number_format_drop_zero_decimals('54.377', 2) ==> 54.38
number_format_drop_zero_decimals(54.377, 3) ==> 54.377
number_format_drop_zero_decimals(54.007, 2) ==> 54.01
number_format_drop_zero_decimals(54.000, 2) ==> 54
number_format_drop_zero_decimals(54.00, 2) ==> 54
number_format_drop_zero_decimals(54.0, 2) ==> 54
number_format_drop_zero_decimals(54.1, 2) ==> 54.10
number_format_drop_zero_decimals(54., 2) ==> 54
number_format_drop_zero_decimals(54, 2) ==> 54
number_format_drop_zero_decimals(54, 3) ==> 54
number_format_drop_zero_decimals(54 + .13, 2) ==> 54.13
number_format_drop_zero_decimals(54 + .00, 2) ==> 54
number_format_drop_zero_decimals(54.0007, 4) ==> 54.0007
number_format_drop_zero_decimals(54.0007, 3) ==> 54.001
number_format_drop_zero_decimals(54.00007, 3) ==> 54 // 注意此處
我們發現從 Ubuntu 10.04 php -v 5.3.2 切換到 Ubuntu 12.04 php -v 5.3.10 後,這個函式就失效了。
<?php setlocale(LC_MONETARY, 'en_US'); ?>
發現使用
<?php setlocale(LC_MONETARY, 'en_US.UTF-8'); ?>
可以正常運作
這個函式會用逗號分隔整數。例如:
<?php
echo formatMoney(1050); # 1,050
echo formatMoney(1321435.4, true); # 1,321,435.40
echo formatMoney(10059240.42941, true); # 10,059,240.43
echo formatMoney(13245); # 13,245
function formatMoney($number, $fractional=false) {
if ($fractional) {
$number = sprintf('%.2f', $number);
}
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number) {
$number = $replaced;
} else {
break;
}
}
return $number;
}
?>
針對 Rafael M. Salvioni 在 Windows 上 money_format 解決方案的改進:當未選擇貨幣符號時,如果地區設定將負號放置在位置 3 或 4,格式化過程中也會遺失負號。 將 $currency = ''; 改為:$currency = $cprefix . $csuffix;
function money_format($format, $number) {
$regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' .
'(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
if (setlocale(LC_MONETARY, 0) == 'C') {
setlocale(LC_MONETARY, '');
}
$locale = localeconv();
preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
foreach ($matches as $fmatch) {
$value = floatval($number);
$flags = array(
'fillchar' => preg_match('/\=(.)/', $fmatch[1], $match) ?
$match[1] : ' ',
'nogroup' => preg_match('/\^/', $fmatch[1]) > 0,
'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
$match[0] : '+',
'nosimbol' => preg_match('/\!/', $fmatch[1]) > 0,
'isleft' => preg_match('/\-/', $fmatch[1]) > 0
);
$width = trim($fmatch[2]) ? (int) $fmatch[2] : 0;
$left = trim($fmatch[3]) ? (int) $fmatch[3] : 0;
$right = trim($fmatch[4]) ? (int) $fmatch[4] : $locale['int_frac_digits'];
$conversion = $fmatch[5];
$positive = true;
if ($value < 0) {
$positive = false;
$value *= -1;
}
$letter = $positive ? 'p' : 'n';
$prefix = $suffix = $cprefix = $csuffix = $signal = '';
$signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
switch (true) {
case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+'
$prefix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+'
$suffix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+'
$cprefix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+'
$csuffix = $signal;
break;
case $flags['usesignal'] == '('
case $locale["{$letter}_sign_posn"] == 0
$prefix = '(';
$suffix = ')';
break;
}
if (!$flags['nosimbol']) {
$currency = $cprefix .
($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
$csuffix;
} else {
$currency = $cprefix .$csuffix;
}
$space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
$value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
$value = @explode($locale['mon_decimal_point'], $value);
$n = strlen($prefix) + strlen($currency) + strlen($value[0]);
if ($left > 0 && $left > $n) {
$value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
}
$value = implode($locale['mon_decimal_point'], $value);
if ($locale["{$letter}_cs_precedes"]) {
$value = $prefix . $currency . $space . $value . $suffix;
} else {
} else { $value = $prefix . $value . $space . $currency . $suffix;
}
if ($width > 0) {
$value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
STR_PAD_RIGHT : STR_PAD_LEFT);
}
$format = str_replace($fmatch[0], $value, $format);
}
return $format;
}
仔細檢查一下 money_format() 是否在你打算運行程式碼的任何 PHP 版本上都有定義。你可能會感到驚訝。
例如,它在我編寫程式碼的 Linux 系統上可以運作,但在運行 BSD 4.11 變體的伺服器上卻不行。(這可能是因為 strfmon 沒有定義 - 請參閱此頁面頂部的註釋)。這不僅僅是 Windows/Unix 的問題。
Rafael M. Salvioni 的程式碼在數值為正且提供的格式包含 ( 旗標時有一個小錯誤。只有在數值為負數時,才應該用括號括起來。這樣應該可以修復它。
<?php
if (!function_exists('money_format'))
{
function money_format($format, $number)
{
$regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'.
'(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
if (setlocale(LC_MONETARY, 0) == 'C') {
setlocale(LC_MONETARY, '');
}
$locale = localeconv();
preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
foreach ($matches as $fmatch) {
$value = floatval($number);
$flags = array(
'fillchar' => preg_match('/\=(.)/', $fmatch[1], $match) ?
$match[1] : ' ',
'nogroup' => preg_match('/\^/', $fmatch[1]) > 0,
'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
$match[0] : '+',
'nosimbol' => preg_match('/\!/', $fmatch[1]) > 0,
'isleft' => preg_match('/\-/', $fmatch[1]) > 0
);
$width = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
$left = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
$right = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
$conversion = $fmatch[5];
$positive = true;
if ($value < 0) {
$positive = false;
$value *= -1;
}
$letter = $positive ? 'p' : 'n';
$prefix = $suffix = $cprefix = $csuffix = $signal = '';
$signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
switch (true) {
case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
$prefix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
$suffix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
$cprefix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
$csuffix = $signal;
break;
case $flags['usesignal'] == '(' && !$positive:
case $locale["{$letter}_sign_posn"] == 0:
$prefix = '(';
$suffix = ')';
break;
}
if (!$flags['nosimbol']) {
$currency = $cprefix .
($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
$csuffix;
} else {
$currency = '';
}
$space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
$value = number_format($value, $right, $locale['mon_decimal_point'],
$flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
$value = @explode($locale['mon_decimal_point'], $value);
$n = strlen($prefix) + strlen($currency) + strlen($value[0]);
if ($left > 0 && $left > $n) {
$value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
}
$value = implode($locale['mon_decimal_point'], $value);
if ($locale["{$letter}_cs_precedes"]) {
$value = $prefix . $currency . $space . $value . $suffix;
} else {
$value = $prefix . $value . $space . $currency . $suffix;
}
if ($width > 0) {
$value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
STR_PAD_RIGHT : STR_PAD_LEFT);
}
$format = str_replace($fmatch[0], $value, $format);
}
return $format;
}
}
?>
嗨,
對於南亞貨幣,這個函數可能很方便。
它可以處理負數以及帶小數的數值(派薩)。
<?php
function my_money_format($number)
{
if(strstr($number,"-"))
{
$number = str_replace("-","",$number);
$negative = "-";
}
$split_number = @explode(".",$number);
$rupee = $split_number[0];
$paise = @$split_number[1];
if(@strlen($rupee)>3)
{
$hundreds = substr($rupee,strlen($rupee)-3);
$thousands_in_reverse = strrev(substr($rupee,0,strlen($rupee)-3));
for($i=0; $i<(strlen($thousands_in_reverse)); $i=$i+2)
{
$thousands .= $thousands_in_reverse[$i].$thousands_in_reverse[$i+1].",";
}
$thousands = strrev(trim($thousands,","));
$formatted_rupee = $thousands.",".$hundreds;
}
else
{
$formatted_rupee = $rupee;
}
if((int)$paise>0)
{
$formatted_paise = ".".substr($paise,0,2);
}
return $negative.$formatted_rupee.$formatted_paise;
}
?>
謝謝,
考慮到某些南亞國家使用 ##,##,###.## 的貨幣格式。
以下程式碼產生的結果類似於 Rs. 4,54,234.00 等等。
<?php
function convertcash($num, $currency){
if(strlen($num)>3){
$lastthree = substr($num, strlen($num)-3, strlen($num));
$restunits = substr($num, 0, strlen($num)-3); // 取出最後三位數
$restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // 將剩餘數字以二位數為一組,如果位數是奇數,則在開頭補零
$expunit = str_split($restunits, 2);
for($i=0; $i<sizeof($expunit); $i++){
$explrestunits .= (int)$expunit[$i].","; // 建立每一個二位數的群組,並在結尾加上逗號
}
$thecash = $explrestunits.$lastthree;
} else {
$thecash = $convertnum;
}
return $currency.$thecash.".00"; // 組合最終格式,其中 $currency 是貨幣符號。
}
?>
現在以 convertcash($row['price'], 'Rs '); 呼叫函式,其中 $row['price'] 是從資料庫取得的價格,使用印度盧比前綴,價格必須是純數字格式,例如 454234。
如果您得到的是「EUR」而不是歐元符號,請將地區設定設為 utf8 字元集,如下所示:
<?php
setlocale(LC_MONETARY, 'de_DE.utf8');
echo money_format('%+n', 1234.56);
?>
這是我剛寫的一小段簡潔的程式碼,因為我找不到其他適合我情況的程式碼。
這段程式碼會處理使用者傳遞給腳本的貨幣值,重新格式化任何逗號的使用方式,使其在通過檢查浮點數的輸入驗證系統時不會出錯。
它並非萬無一失,但可以處理大多數使用者輸入的常見格式,例如 1,234,567(輸出 1234567)或 1,234.00(輸出 1234.00),甚至可以處理 12,34(輸出 12.34)。我預計它也適用於負數,但尚未測試,因為在我的情況下並未使用到。
當其他選項(例如 money_format())不適用或不可行時,這個方法有效。
<?php
///////////////
// 開始程式碼:將所有價格金額轉換為格式良好的值
function converttonum($convertnum,$fieldinput){
$bits = explode(",",$convertnum); // 將輸入值分割,以便檢查
$first = strlen($bits[0]); // 取得第一個逗號之前的部分(千位/百萬位)
$last = strlen($bits[1]); // 取得第一個逗號之後的部分(千位(或者如果使用者錯誤使用,則為小數位)
if ($last <3){ // 檢查逗號是否被用作小數點
$convertnum = str_replace(",",".",$convertnum);
}
else{ // 假設逗號是千位分隔符號,因此將其移除
$convertnum = str_replace(",","",$convertnum);
}
$_POST[$fieldinput] = $convertnum; // 重新定義變數的值為新的修正值
}
@converttonum($_POST[inputone],"inputone");
@converttonum($_POST[inputtwo],"inputtwo");
@converttonum($_POST[inputthree],"inputthree");
// 結束程式碼
//////////////
?>
這適用於英文用法,可能需要調整才能適用於其他類型。
對小數位數超過兩位的浮點數值使用 money_format 函數可能會導致捨入錯誤。
也許這個函數可以幫助您避免這些錯誤
<?php
// A product with a base price of 12.95
$price = 1295;
// The quantity is also an integer but translated it would be 11.91
$quantity = 1191;
// Result: 154.2345
// It's the same like 12.95 * 11.91
$sum = ($price / 100) * ($quantity /100);
// Wrong result: 154.23
money_format('%!i', $sum);
// Wrong result: 154.23
number_format($sum, 2);
// Wrong result: 154.23
bcmul($price / 100, $quantity / 100, 2);
// Correct result : 154.24
money_format_rounded('%!i', $sum);
/**
* Formats a number as a currency string. Rounds every decimal digit to a defined precision on its own.
*
* @param string $format The format for the money_format function
* @param float|int|string $number The number to be formatted
* @param int $maxPrecision Round up to the $maxPrecision number of decimal digit. Default is: 2
* @param int $roundingType Rounding type for the round function. Default is: \PHP_ROUND_HALF_UP
*
* @return string
*/
function money_format_rounded($format, $number, $maxPrecision = 2, $roundingType = \PHP_ROUND_HALF_UP)
{
$strlen = strlen($number);
if ($strlen === 0) {
return money_format($format, $number);
}
$length = $strlen - strrpos($number, '.') - 1;
if ($length <= 0) {
return money_format($format, $number);
}
$rounded = $number;
for ($i = --$length; $i >= $maxPrecision; $i--) {
$rounded = round($rounded, $i, $roundingType);
}
return money_format($format, $rounded);
}
請注意,由於 PHP 7.3 已將此方法標記為棄用,並且從 PHP 7.4 開始會觸發棄用錯誤,因此,請設定您的 PHP 網頁伺服器以忽略 E_DEPRECATED 錯誤報告。