Results 1 to 9 of 9
  1. #1

    how do I show a number up to 2 decimal places?

    I'm using mysql and php to download a data type that should be in currency format. I have chosen a datatype of float to show the numbers past the decimal place but they go on too long. I only want it to go to 2 decimal places...
    Can any one help?

  2. #2
    Join Date
    Nov 2007
    Hi tttt, you could always use the PHP number_format function:

    $varnewnum = number_format($varoldnum,2);

    In the example above, $varoldnum is the variable for the floating number you have queried. This will return the number formatted down to 2 decimal places.
    Canvas Host, LLC - - 800.574.4299
    cPanel shared and reseller plans. Softaculous, RVSiteBuilder.
    200% renewable wind power offset, sustainable practices, certified B Corporation.
    30-Day Money-Back, 99.9% Uptime, No-Oversell.

  3. #3
    Thank you! it works

  4. #4
    Join Date
    Feb 2003
    L.A. C.A.
    number_format may work, but the real solution is found in round(number, places) e.g. echo round($number, 2); - A collection of my programmer thoughts

  5. #5
    Join Date
    Nov 2005
    number_format() will round the number to the specified decimal place. It will return a string, suitable to, as op says, "show the numbers": number_format(4.00987) will echo as "4.01". round() won't show trailing decimal zeroes: round(4.000123) will echo as "4". If calculations are to be done, they will pesumably be done with the unaltered float.

  6. #6
    Join Date
    May 2008
    Rutherford, NJ
    Agreed, definitely use number_format. You don't want $4.50 to show up as '$4.5'. Just be sure to only do this when it is displayed, as rounding before will affect calculations, and the return is a string rather than a float.
    Database design and performance optimization, custom PHP scripts, and publicly available resources for developers!

  7. #7
    what about sprintf? can do the same thing as number_format

  8. #8
    thank everyone for your feedback you have all taught me something new...

  9. #9
    Join Date
    Nov 2005
    I'd like to correct the typo in my earlier post:
    number_format(4.00987) will echo as "4.01"
    Should be:
    number_format(4.00987, 2) will echo as "4.01"

    Also, to make the point clearer:
    round(4.000123) will echo as "4"
    Should be:
    round(4.000123, 2) will echo as "4"
    Last edited by bigfan; 05-16-2008 at 09:12 AM.

Posting Permissions

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