php number_format给出错误信息

时间:2011-12-25 06:26:56

标签: php xml

我使用php来解析XML文件,但在尝试显示格式化的数字时收到错误消息:

警告:number_format()要求参数1加倍,第45行/home/chesspro/public_html/UNYCL/people-8.php中给出的对象

<?php 
$xml = simplexml_load_file('Rochester_1.xml');

foreach($xml->meet as $item) {

    print '<table class="basic report tableland brown_gradient"><thead>';
    print '<tr><th class="R-align">Board</th><th class="L-align">'.$item->visitor.'</th>';

    $subtotal = 0;
    foreach($item->match as $temp) {$subtotal = $subtotal + $temp->white->score;}
    print "<th>" .number_format($subtotal,1). "</th>";

    $subtotal = 0;
    foreach($item->match as $temp) {$subtotal = $subtotal + $temp->black->score;}
    print "<th>" .number_format($subtotal,1). "</th>";

    print '<th class="L-align">'.$item->home.'</th>';

    print '</tr><tbody>';

    foreach($item->match as $game) {

    print '<tr><td class="R-align">'. $game->board . "</td>";
    print '<td>'. $game->white->player."</td>";

    //Here is error: note that number is sometimes 0
        $X = $game->white->score;
        print '<td>'. number_format($X) ."</td>";

    print '<td>'. $game->black->score."</td>";       
    print '<td class="L-align">'. $game->black->player."</td>";

    print "</tr>";}
print '</table>';}
?>

现在可以解决这个问题吗?我需要一个十进制精度点(X.X),虽然有些数字是像“7”这样的整数,我想格式化并显示为“7.0”注意我使用的是近期的php版本5.3.4

2 个答案:

答案 0 :(得分:2)

print '<td>'. number_format($X, 1) ."</td>";

请参阅http://php.net/manual/en/function.number-format.php

如果这不起作用,请尝试输入:http://us3.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting

$X = (float)$game->white->score;
print '<td>'. number_format($X) ."</td>";

答案 1 :(得分:1)

看起来像$game->white->score不返回float或int。 尝试这样做 $X = (float)$game->white->score; print '<td>'. number_format($X) ."</td>";

但是带有一个参数的number_format()将返回以千位为单位的数字,因此如果您想要7.0,请更好地使用print '<td>'. number_format($X,1) ."</td>";