What is the exact equivalent of JS: something.toFixed() in PHP?

前端 未结 7 1464
Happy的楠姐
Happy的楠姐 2020-12-30 06:36

If I have a.toFixed(3); in javascript (\'a\' being equal to 2.4232) what is the exact equivalent command in php to retrieve that? I searched for it but found n

相关标签:
7条回答
  • 2020-12-30 06:50

    In PHP you can use a function called round.

    0 讨论(0)
  • 2020-12-30 06:59

    A direct equivalent is sprintf('%.03F', $a). This will format the value in question as a number with 3 decimal digits. It will also round if required.

    0 讨论(0)
  • 2020-12-30 07:01

    I found that sprintf and number_format both round the number, so i used this:

    $number = 2.4232;
    $decimals = 3;
    $expo = pow(10,$decimals);
    $number = intval($number*$expo)/$expo; //  = 2423/100
    
    0 讨论(0)
  • 2020-12-30 07:01

    The exact equivalent command in PHP is function number_format:

    number_format($a, 3, '.', ""); // 2.423
    
    • it rounds the number to the third decimal place
    • it fills with '0' characters if needed to always have three decimal digits

    Here is a practical function:

    function toFixed($number, $decimals) {
      return number_format($number, $decimals, '.', "");
    }
    
    toFixed($a, 3); // 2.423
    
    0 讨论(0)
  • 2020-12-30 07:05

    The straight forward solution is to use in php is number_format()

    number_format(2.4232, 3);
    
    0 讨论(0)
  • 2020-12-30 07:07

    Have you tried this:

    round(2.4232, 2);
    

    This would give you an answer of 2.42.

    More information can be found here: http://php.net/manual/en/function.round.php

    0 讨论(0)
提交回复
热议问题