如何在一个数字的每3位数字中加逗号

时间:2012-11-13 06:00:12

标签: php

例如,我想在数字的每3位数字中加逗号。

$number = 1234567;
// should print 1,234,567

我该怎么做?

更新:请参阅此代码

<?php
/**
 * Get Popularity Text of a Domain via Alexa XML Data
 *
 * @return string|FALSE text or FALSE on error
 */
function alexa_get_rank($domain)
{
    $alexa = "http://data.alexa.com/data?cli=10&dat=s&url=%s";
    $request_url =  sprintf($alexa, urlencode($domain));


    $xml = simplexml_load_file($request_url);
    if (!$xml) {
        return FALSE;
    }

    $nodeAttributes = $xml->SD[1]->POPULARITY->attributes();
    $text = (int) $nodeAttributes['TEXT'];

    $num = number_format($text);

    return $num;
}

仅返回3位数。

8 个答案:

答案 0 :(得分:18)

使用

echo number_format('1234567');

PHP Manual : number_format()

答案 1 :(得分:2)

试试这个:

$number = 1234567;
echo number_format($number);

使用this作为参考号

答案 2 :(得分:1)

$number = 123456789;
$number = number_format($number);
echo $number;

答案 3 :(得分:1)

请参阅number_format

<?php
echo number_format(1234567890); //1,234,567,890

答案 4 :(得分:0)

<?
$number = 1234567;
echo number_format($number); // this returns : 1,234,567
?>

详细了解number_format();

答案 5 :(得分:0)

$number = 1234.56;

//english notation (default)
$english_format_number = number_format($number);// 1,235


// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');// 1 234,56


//----------------------------------------------


$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');// 1234.57

点击number_format() php.net了解详情。

答案 6 :(得分:0)

 $num = 1234567.65;
 $num = number_format($num);
 echo $num; // $num = 1,234,568

答案 7 :(得分:0)

要设置数字格式,可以使用number_format

尝试以下代码:

$number=1234567;  
$number_format=number_format($number,0,".",","); // return 1,234,567