2011-12-25 131 views
3

我使用PHP来解析XML文件,但我得到试图显示格式的数字时的错误消息:PHP number_format给出错误信息

警告:number_format()预计参数1双待,对象给出在/home/chesspro/public_html/UNYCL/people-8.php在线45

<?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>';} 
?> 

现在可以解决这个问题?我需要小数精度(XX)中的一个点,尽管一些号码,如“7”的整数,我想格式化而显示为“7.0”请注意,我用的是接近目前的PHP版本5.3.4

+0

它的工作原理,当你将其更改为:'$小计= $ subtotal + floatval((string)$ temp-> white-> score);'? – vstm 2011-12-25 06:32:09

回答

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>"; 
+0

绝对完美!结果在:http://rochesterchesspro.com/UNYCL/people-8.php谢谢你们两位! – verlager 2011-12-25 06:48:52

+1

警告:浮球是危险的。例如:而不是11,将其转换为浮点数可能会导致10.999999999999999 – 2017-12-21 01:39:56

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>";