Search code examples
phpformattingdecimal

Print numeric values to two decimal places


I'm using a simple loop to echo back some numbers.

<?php
$inc = 0.25;
$start =  0.25;
$stop = 5.00;
?>
        
<?php while($start != ($stop + $inc)){ ?>
<option><?php echo $start ?></option>
<?php $start = $start + $inc; ?>
<?php } ?>

However 5.00 appears as 5 and 4.50 appears as 4.5.

How would I get this script to display 5.00, 4.00, 3.00, 3.50?


Solution

  • use this:

    printf("%01.2f", $start)
    

    or if you need to store it to variable

    $var = sprintf("%01.2f", $start)
    

    You can also use number_format, this is good when you need to format that in some country formatting rules. You can provide decimal and thousand separator

    number_format($start, 2)