Default Number of Decimal Places to Output in PHP

前端 未结 6 1343
执念已碎
执念已碎 2020-12-18 13:37

I do my php work on my dev box at home, where I\'ve got a rudimentary LAMP setup. When I look at my website on my home box, any numbers I echo are automatically truncated t

相关标签:
6条回答
  • 2020-12-18 14:15

    You should use the round() command to always round down the precision you want, otherwise some day you'll get something like 2.2000000000123 due to the nature of float arithmetic.

    0 讨论(0)
  • 2020-12-18 14:16

    And when you can't rely on the PHP configuration, don't forget about number_format() which you can use to define how a number is returned, ex:

    // displays 3.14 as 3 and 4.00 as 4    
    print number_format($price, 0); 
    // display 4 as 4.00 and 1234.56 as 1,234.56 aka money style
    print number_format($int, 2, ".", ","); 
    

    PS: and try to avoid using money_format(), as it won't work on Windows and some other boxes

    0 讨论(0)
  • 2020-12-18 14:16

    A quick look through the available INI settings makes me thing your precision values are different?

    0 讨论(0)
  • 2020-12-18 14:20

    thanks for all the answers - the solution was to cast the return value of the method responsible to a float. I.e. it was doing

    return someNumber.' grams';
    

    I just changed it to

    return (float)someNumber.' grams';
    

    then PHP truncated any trailing zeroes when required.

    Can someone close this?

    0 讨论(0)
  • 2020-12-18 14:29

    Just to rule out other possible causes: Where are the numbers coming from? Does it do this with literal values?

    It doesn't seem likely that the precision setting alone could cause this. Check also if anything might be interfering with the output via things like auto_prepend_file or output_handler.

    0 讨论(0)
  • 2020-12-18 14:29

    Try the built in function round;

    float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] );
    

    Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

    Example #1 round() examples

    <?php
    echo round(3.4);         // 3
    echo round(3.5);         // 4
    echo round(3.6);         // 4
    echo round(3.6, 0);      // 4
    echo round(1.95583, 2);  // 1.96
    echo round(1241757, -3); // 1242000
    echo round(5.045, 2);    // 5.05
    echo round(5.055, 2);    // 5.06
    ?>
    

    Example #2 mode examples

    <?php
    echo round(9.5, 0, PHP_ROUND_HALF_UP);   // 10
    echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
    echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
    echo round(9.5, 0, PHP_ROUND_HALF_ODD);  // 9
    
    echo round(8.5, 0, PHP_ROUND_HALF_UP);   // 9
    echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
    echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
    echo round(8.5, 0, PHP_ROUND_HALF_ODD);  // 9
    ?>
    
    0 讨论(0)
提交回复
热议问题