How do do a thousand separator (like a comma) in a printf
?
example:
printf("<td class='number'>%d</td>", $totals['Sold']); //need thousand separated
printf("<td class='number'>%.2f</td>", $totals['Fees']); //need thousand separated
UPDATE this is what i had originally:
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>";
and I want it to be come something like:
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>";
But I need the commas
we can use my_string = '{:,. 2f}'. format(my_number) to convert float value into commas as thousands separators.
The character used as the thousands separator In the United States, this character is a comma (,). In Germany, it is a period (.). Thus one thousand and twenty-five is displayed as 1,025 in the United States and 1.025 in Germany. In Sweden, the thousands separator is a space.
Reference. Per Format Specification Mini-Language, The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.
Make your code pretty and don't echo it all. Just break out of PHP context to do it, and then instead of printf just echo using number_format:
</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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With