1

我有以下功能:

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return __('0 View','mm');
    }
    return $count. __(' Views','mm'); 
}

如何使其格式化数字以在千分位中包含逗号?例如,50000 应该变成 50,000。

4

5 回答 5

3

使用number_format()

number_format($number);
于 2012-05-03T02:03:52.640 回答
2

看看number_format

例如:

$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
于 2012-05-03T02:04:21.047 回答
2

您可以使用number_format.

于 2012-05-03T02:04:23.413 回答
0
$number=number_format($number);
于 2012-05-03T02:03:39.223 回答
0

您的数字格式使用正确,以获得您正在寻找的漂亮格式。我认为您在更改数据库格式时遇到的问题是您正在格式化数字并将其重新保存。

例如:

$count = 5000;
$count = number_format($count);
//$count is no longer equal to 5000, it is now a string 5,000

尝试使用一个临时变量,这样你原来的 $count 变量就不会改变,当你写回数据库时,它仍然是你想要的格式。

例如:

$count = 5000;
$tmpCount = 0;
$tmpCount = number_format($count);
// $count is still 5000, and $tmpCount now holds the value 5,000.

您的代码的更新版本,我假设您只希望元数据包含逗号分隔值?

    function setPostViews($postID) {
    //Set initial variables
    $count_key = 'post_views_count';
    $tmpCount = 0;
    $count = get_post_meta($postID, $count_key, true);

    if($count == '') {
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    } else {
        $count++;
        //Set tmpCount variable to hold comma separated value
        $tmpCount = number_format($count);

        //Comma separated value is passed into your function
        update_post_meta($postID, $count_key, $tmpCount);
    }
}

那是你所希望的吗?或者,如果您只想在向用户显示时以这种方式格式化此数字,但 db 保持正确(不是逗号分隔),在查询 db 后,保存 db 值并完全按照我创建一个逗号分隔的变量'上面已经完成了。然后在任何 db 函数上,引用 $count 变量,在任何用户输出函数上,使用 $tmpCount 变量。

再次,我希望能回答你的问题,如果不是,请澄清。

于 2012-05-04T00:18:39.833 回答