Nea*_*eal 4 php printf number-formatting
如何在一个千位分隔符(如逗号)printf?
例:
printf("<td class='number'>%d</td>", $totals['Sold']); //need thousand separated
printf("<td class='number'>%.2f</td>", $totals['Fees']); //need thousand separated
Run Code Online (Sandbox Code Playgroud)
更新这是我原来的:
foreach(array_keys($totals) as $key){
if(is_numeric($totals[$key])){
$totals[$key] = number_format($totals[$key],2);
}
}
echo "</tbody>
<tfoot><tr>";
echo "<td class='text' colspan='4'>Totals:</td>";
echo "<td class='number'>{$totals['Bought']}</td>";
echo "<td class='number'>{$totals['Sold']}</td>";
echo "<td class='number'>{$totals['Fees']}</td>";
echo "<td class='number'>{$totals['Realized']}</td>";
echo "<td class='number'>{$totals['Net']}</td>";
echo "<td colspan='3'>{$totals['EOD Price']}</td>";
echo "</tr>
</tfoot>";
Run Code Online (Sandbox Code Playgroud)
我希望它能像:
echo "</tbody>
<tfoot><tr>";
echo "<td class='text' colspan='3'>Totals:</td>";
printf("<td class='number'>%d</td>", $totals['Bought']) ;
printf("<td class='number'>%d</td>", $totals['Sold']) ;
printf("<td class='number'>%.2f</td>", $totals['Fees']) ;
printf("<td class='number'>%.2f</td>", $totals['Realized']) ;
printf("<td class='number'>%.2f</td>", $totals['Net']) ;
printf("<td colspan='3'>%.2f</td>", $totals['EOD Price']) ;
echo "</tr>
</tfoot>";
Run Code Online (Sandbox Code Playgroud)
但我需要逗号
让你的代码漂亮,不要回应所有.刚刚打破PHP上下文来做,然后使用number_format而不是printf只是echo:
</tbody>
<tfoot>
<tr>
<td ...>Totals</td>
<td ...><?php echo number_format($totals['Bought'], 0); ?></td>
<td ...><?php echo number_format($totals['Sold'], 0); ?></td>
<td ...><?php echo number_format($totals['Fees'], 2); ?></td>
...
</tr>
</tfoot>
Run Code Online (Sandbox Code Playgroud)
您可以使用number_format函数.
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
Run Code Online (Sandbox Code Playgroud)
http://php.net/manual/en/function.number-format.php