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

前端 未结 6 1070
抹茶落季
抹茶落季 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:02

    This is simple and it will also let you tweak the format to taste:

    $var = sprintf($var == intval($var) ? "%d" : "%.2f", $var);
    

    It will format the variable as an integer (%d) if it has no decimals, and with exactly two decimal digits (%.2f) if it has a decimal part.

    See it in action.

    Update: As Archimedix points out, this will result in displaying 3.00 if the input value is in the range (2.995, 3.005). Here's an improved check that fixes this:

    $var = sprintf(round($var, 2) == intval($var) ? "%d" : "%.2f", $var);
    

提交回复
热议问题