Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Feb 2006
    Posts
    32
    Thanks
    2
    Thanked 0 Times in 0 Posts

    PHP math operations

    Hello,

    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 Code:
    <?php echo $_POST["price"]*0.9?>

  • #2
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Posts
    951
    Thanks
    1
    Thanked 31 Times in 29 Posts
    PHP Code:
    <?php echo sprintf('%.2f'$_POST["price"]*0.9); ?> 
    or
    <?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.
    Last edited by ralph l mayo; 05-12-2006 at 04:41 AM.

  • #3
    Regular Coder
    Join Date
    Sep 2005
    Posts
    394
    Thanks
    1
    Thanked 0 Times in 0 Posts
    <?php echo number_format($_POST["price"]*0.9, 2); ?>

    That outputs to 2dp.

    ~Phil~

  • #4
    New Coder
    Join Date
    Feb 2006
    Posts
    32
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thanks!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •