在 php 中添加逗号作为千位分隔符和浮点点

2022-08-30 20:36:36

我有这个

$example = "1234567"
$subtotal =  number_format($example, 2, '.', '');

$subtotal的回归是如何修改$subtotal的定义,让它变成这样"1234567.00""1,234,567.00"


答案 1

下面将输出1,234,567.00

$example = "1234567";
$subtotal =  number_format($example, 2, '.', ',');
echo $subtotal;

语法

string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )

但是我建议您使用money_format它将数字格式化为货币字符串


答案 2

你有很多选择,但money_format可以为你解决问题。

// Example:

$amount = '100000';
setlocale(LC_MONETARY, 'en_IN');
$amount = money_format('%!i', $amount);
echo $amount;

// Output:

"1,00,000.00"

请注意,仅当系统具有功能时才定义。例如,Windows 没有,因此它在 Windows 中是未定义的。money_format()strfmon

最终编辑:这是一个纯PHP实现,可以在任何系统上工作:

$amount = '10000034000';
$amount = moneyFormatIndia( $amount );
echo number_format($amount, 2, '.', '');

function moneyFormatIndia($num){
    $explrestunits = "" ;
    if(strlen($num)>3){
        $lastthree = substr($num, strlen($num)-3, strlen($num));
        $restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
        $restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
        $expunit = str_split($restunits, 2);
        for($i=0; $i<sizeof($expunit); $i++){
            // creates each of the 2's group and adds a comma to the end
            if($i==0){
                $explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer
            }else{
                $explrestunits .= $expunit[$i].",";
            }
        }
        $thecash = $explrestunits.$lastthree;
    } else {
        $thecash = $num;
    }
    return $thecash; // writes the final format where $currency is the currency symbol.
}

推荐