PHP show only significant (non-zero) decimals

前端 未结 11 1256
借酒劲吻你
借酒劲吻你 2021-01-07 19:32

In PHP (using built-in functions) I\'d like to convert/format a number with decimal, so that only the non-zero decimals show. However, another requirement of mine is that if

11条回答
  •  借酒劲吻你
    2021-01-07 19:53

    My solution is to let php handle it as a number (is *1) and then treat it as a string (my example I was using percentages stored as a decimal with 2 decimal places):

    printf('%s%% off', $value*1);
    

    This outputs:

    0.00  => 0% off
    0.01  => 0.01% off
    20.00 => 20% off
    20.50 => 20.5% off
    

提交回复
热议问题