PHP number: decimal point visible only if needed

后端 未结 12 1792
死守一世寂寞
死守一世寂寞 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:51

    You could also use rtrim(), which would remove excess 0s, in the case where you might want to keep one decimal place but not the excess zeros. (For example, 4.50 becomes 4.5.) Also allows you to change the number of decimal places from 2 to any other number.

    rtrim(rtrim((string)number_format($value, 2, ".", ""),"0"),".");
    
    // 4.00 -> 4
    // 4.50 -> 4.5
    // 4.54000000 -> 4.54 (if you're doing more decimal places)
    

提交回复
热议问题