View Full Version : PHP math operations
05-12-2006, 03:27 AM
With code such as the example below, how do I get PHP to round the output to 2 decimal places (it is a price)?
<?php echo $_POST["price"]*0.9; ?>
ralph l mayo
05-12-2006, 04:37 AM
<?php echo sprintf('%.2f', $_POST["price"]*0.9); ?>
<?php printf('%.2f', $_POST["price"]*0.9); ?>
sprintf is pretty versatile, there's a lot more to learn in the docs if this isn't a one-off deal, and it translates well across languages so it's a good general purpose utility to familiarize yourself with. This format means use two decimal places and interpret the second parameter as a float when returning.
It can pipe to the output or just return depending on which version you use.
05-12-2006, 08:17 AM
<?php echo number_format($_POST["price"]*0.9, 2); ?>
That outputs to 2dp.
05-15-2006, 07:53 PM
Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.