2011-12-25 80 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>";