PHP number: decimal point visible only if needed

后端 未结 12 1591
死守一世寂寞
死守一世寂寞 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: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);
    }
    

提交回复
热议问题