Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thousands separator with printf

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

like image 734
Naftali Avatar asked May 03 '11 18:05

Naftali


People also ask

How do you print numbers with commas as thousands separators?

we can use my_string = '{:,. 2f}'. format(my_number) to convert float value into commas as thousands separators.

What is the thousand separator format?

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.

Which is a thousand separator in Python?

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.


1 Answers

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>
like image 164
ircmaxell Avatar answered Nov 15 '22 08:11

ircmaxell