Number format

Hi Guys i have a simple form that selects items with a fixed price.

when i select submit the unit price will shoe a double figure for example 3.50 but the price and total amounts only show a single figure for example 3.5

how do i get these to change to double figures.

Full working example

the form action is code.php and this is it


$totalprice = 0;
// checkbox values
echo "Name: ".$_POST['name'];
echo "<table cellpadding=3 border=0 style='float:left'>";

echo "<tr style=\"background-color:#333333; color:white;\"><th>Item</th><th>Unit Price</th><th>Qnty</th><th>Price</th></tr>";

    $qnty = $_POST['qnty'];

    if(!empty($_POST['lang'])) {
        $l = $_POST['lang'];

        foreach($l as $value){
            $v = explode("::",$value);
            $q = $qnty[$v[0]-1];
            $p = $v[2]*$qnty[$v[0]-1];
            echo "<tr style=\"background-color:#dddddd; color:black;\"><td>".$v[3]."</td><td>".$v[2]."</td><td>".$q."</td><td>".$p."</td></tr>";
            $totalprice +=  $p;


echo "<tr style=\"background-color:#003366; color:white;\"><td colspan=\"3\"><b>Total Amount</b></td><td><b>$totalprice</b></td></tr>";
echo "</table>";

any advice thanks

You can use sprintf to format a number in different ways. In your case, replace


With this:

<td><b>" . sprintf("%.2f", $p) . "</b></td>



with this:

<td><b>" . sprintf("%.2f", $totalprice) . "</b></td>

The first argument, "%.2f" is a format string. They can do a lot. This one goes as follows:

  • % specifies that we’re starting a placeholder - something to replace with the second argument.
  • f specifies that we’re formatting a float rather than an integer.
  • .2 specifies that the format should include at least two characters after the decimal point. This will do different things if we are formatting different types of value.
1 Like

Thank you for your help i understand now how this works/

An alternative is to use number_format().

Sponsor our Newsletter | Privacy Policy | Terms of Service