Добавить запятые в качестве разделителя тысяч и точки с плавающей точкой в ​​php - программирование
Подтвердить что ты не робот

Добавить запятые в качестве разделителя тысяч и точки с плавающей точкой в ​​php

У меня есть это

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

возвращает $subtotal "1234567.00" как изменить определение $subtotal, сделать это так: "1,234,567.00"

4b9b3361

Ответ 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"

Обратите внимание, что money_format() определяется только в том случае, если система имеет возможности strfmon. Например, Windows не работает, поэтому в Windows это undefined.

Заключительное редактирование: здесь выполняется чистая реализация 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 formats, adds a zero in the beginning to maintain the 2 grouping.
        $expunit = str_split($restunits, 2);
        for($i=0; $i<sizeof($expunit); $i++){
            // creates each of the 2 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.
}

Ответ 3

Ссылка: http://php.net/manual/en/function.money-format.php

string money_format ( string $format , float $number )

Пример:

// let print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56

Примечание. Функция money_format() определяется только в том случае, если система имеет функции strfmon. Например, Windows не делает этого, поэтому money_format() undefined в Windows.

Примечание. Категория LC_MONETARY настроек локали влияет на поведение этой функции. Используйте setlocale(), чтобы установить соответствующую локаль по умолчанию перед использованием этой функции.

Используйте number_format: http://www.php.net/manual/en/function.number-format.php

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

$number        = 123457;
$format_number = number_format($number, 2, '.', ',');
// 1,234.57