PHP number: decimal point visible only if needed

后端 未结 12 1578
死守一世寂寞
死守一世寂寞 2021-01-31 06:48

I\'d like to know if exists some function to automatically format a number by it\'s decimal, so if I have:



        
相关标签:
12条回答
  • 2021-01-31 07:28

    Actually I think the cleanest way I can think of to do this for someone that just did a search looking for this sort of thing is to do this:

    ( number_format ($sql_result["col_number"], 2) * 100 ) / 100;
    
    0 讨论(0)
  • 2021-01-31 07:31

    If you are targeting US currency I like to use this method:

    function moneyform($number, $symbol = true) {
        return str_replace(".00", "", money_format(($symbol? '%.2n' : "%!n"), $number));
    }
    
    moneyform(1300999);
    -->$1,300,999
    
    moneyform(2500.99);
    -->$2,500.99
    
    moneyform(2500.99, false);
    -->2,500.99
    
    0 讨论(0)
  • 2021-01-31 07:33

    Since I could not find a flexible solution I wrote a simple function to get the best result:

    function getValueFormattedWithMinimalDecimals($value, $max_decimals = 2, $dec_point = ',', $thousands_sep = '') {
        $bestNumberOfDecimals = -1;
        $decimal = 0;
        while ($decimal <= $max_decimals) {
            $bestNumberOfDecimals = $decimal;
            $valueDecimals = number_format($value, $decimal);
            if (floatval($value) == $valueDecimals) {
                break;
            }
            $decimal++;
        }
        if($bestNumberOfDecimals > 0 && number_format($value, $bestNumberOfDecimals) == number_format($value, 0)) {
            $bestNumberOfDecimals = 0;
        }
    
        return number_format($value, $bestNumberOfDecimals, $dec_point, $thousands_sep);
    }
    
    0 讨论(0)
  • 2021-01-31 07:35

    What about

    number_format($value,2) - 0;
    
    0 讨论(0)
  • 2021-01-31 07:38

    I've been accused of doing something like this:

     floatval($foo) == intval($foo) ? number_format($foo) : number_format($foo,2);
    
    0 讨论(0)
  • 2021-01-31 07:38

    Mine since most quantity or pieces do not require decimal, this function will only show decimal when needed.

    str_replace(".00", "", number_format($this->pieces, 2));
    
    0 讨论(0)
提交回复
热议问题