PHP number: decimal point visible only if needed

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

    floatval or simply casting to float

    php > echo floatval(7.00);
    7
    php > echo floatval(2.30);
    2.3
    php > echo floatval(1.25);
    1.25
    php > echo floatval(1.125);
    1.125
    
    php > echo (float) 7.00;
    7
    php > echo (float) 2.30;
    2.3
    php > echo (float) 1.25;
    1.25
    php > echo (float) 1.125;
    1.125
    
    0 讨论(0)
  • 2021-01-31 07:43

    Warren.S answer helped me out. I didn't need the number_format function, so I just did this

    $value=$value-0;
    

    But in the OP's case, he needs number_format to remove the commas. So this would work for him

    $value=number_format ($sql_result["col_number"], 2, ".", "")-0;
    
    0 讨论(0)
  • 2021-01-31 07:47

    I actually think that your workaround is as good as any. It's simple and clear, and there's really no point talking about performance here, so just go for it.

    0 讨论(0)
  • 2021-01-31 07:47

    As Emil says yours are good. But if you want to remove 0 from e.g. 7.50 too, I've got a suggestion, rtrim():

    <?php
        // if $sql_result["col_number"] == 1,455.50
        rtrim(rtrim(number_format($sql_result["col_number"], 2, ".", ""), '0'), '.');
        // will return 1455.5
    ?>
    
    0 讨论(0)
  • 2021-01-31 07:49

    I add the article Remove useless zero digits from decimals in PHP as a nicer way to clean the value without loose decimal if needed.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题