Reputation: 41433
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
?
Upvotes: 0
Views: 3297
Reputation: 2218
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)
Upvotes: 7
Reputation: 1
$price1 = 6.67; $price2 = 5.55; $total = $price1 + $price2;
echo $total;
echo "\n";
//the . means dot position, 4 means 4 digits after the .
$result= sprint("%0.4f", $total);
echo $result;
outputs: 12.22 12.2200
f means float (maybe obvious maybe not:) can try above code by changing the number after the . to get whatever number of digits you want.
Upvotes: 0
Reputation: 4258
You'll want to use printf()
for formatted strings:
printf("%01.2f", $start)
The full manual for (s)printf can be found here
Upvotes: 2
Reputation: 1567
There also is number_format that lets you choose the thousand and decimal separators: http://de.php.net/manual/en/function.number-format.php
Upvotes: 4
Reputation: 8773
<?php while($start != ($stop + $inc)){ ?>
<option><?php printf('%01.2f', $start) ?></option>
<?php $start = $start + $inc; ?>
<?php } ?>
Upvotes: 1