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 https://www.mywebchambers.co.uk/sample

the form action is code.php and this is it

<?php

$totalprice = 0;
// checkbox values
if(isset($_POST['name'])){
echo "Name: ".$_POST['name'];
echo"<br/><br/>";
}
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>";

if(isset($_POST['submit'])){
    $qnty = $_POST['qnty'];

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

        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;
            $i++;
        }

    }

}
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

<td><b>$p</b></td>

With this:

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

and

<td><b>$totalprice</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