PHP Knowledge Base
Formatting Numbers: How to Always Get 2 Decimal Places
Example
<?php $price1 = 0.1; $price2 = 12; $price3 = 0.05; $price1 = sprintf('%0.2f', $price1); $price2 = sprintf('%0.2f', $price2); $price3 = sprintf('%0.2f', $price3); echo "<p>\$price1 = $price1</p>"; echo "<p>\$price2 = $price2</p>"; echo "<p>\$price3 = $price3</p>"; ?>
Demo
$price1 = 0.10
$price2 = 12.00
$price3 = 0.05