In PHP, how to print a number with 2 decimals, but only if there are decimals already?

前端 未结 6 1038
抹茶落季
抹茶落季 2021-01-14 08:33

I have a basic index.php page with some variables that I want to print in several places - here are the variables:



        
6条回答
  •  鱼传尺愫
    2021-01-14 09:23

    What about something like this :

    $value = 15.2; // The value you want to print
    
    $has_decimal = $value != intval($value);
    if ($has_decimal) {
        echo number_format($value, 2);
    }
    else {
        echo $value;
    }
    


    Notes :

    • You can use number_format() to format value to two decimals
    • And if the value is an integer, just display it.

提交回复
热议问题