PHP show only significant (non-zero) decimals

前端 未结 11 1273
借酒劲吻你
借酒劲吻你 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:51

    If you want a built-in solution and you're using a PHP version later than 4.2 you could try floatval():

    echo floatval(9.200);
    

    prints

    9.2
    

    but

    echo floatval(9.123);
    

    prints

    9.123
    

    Hope this helps.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-07 19:59

    I don't think theres a way to do that. A regex is probably your best solution:

    $value = preg_replace('/(\.[0-9]+?)0*$/', '$1', $value);
    

    Demo:

    php> $a = array('0.000', '0.0001', '0.0101', '9.000', '9.100', '9.120', '9.123');
    php> foreach($a as $b) { echo $b . ' => ' . preg_replace('/(\.[0-9]+?)0*$/', '$1', $b)."\n"; }
    0.000 => 0.0
    0.0001 => 0.0001
    0.0101 => 0.0101
    9.000 => 9.0
    9.100 => 9.1
    9.120 => 9.12
    9.123 => 9.123
    
    0 讨论(0)
  • 2021-01-07 20:00
    <?php
        $numbers = array(
            "9.000",
            "9.100",
            "9.120",
            "9.123"
        );
        foreach($numbers as $number) {
            echo sprintf(
                "%s -> %s\n",
                $number,
                (float) $number == (int) $number ? number_format($number, 1) : (float) $number
            );
        }
    ?>
    

    Output:

    9.000 -> 9.0
    9.100 -> 9.1
    9.120 -> 9.12
    9.123 -> 9.123
    
    0 讨论(0)
  • 2021-01-07 20:11

    A trailing zero is significant:

    • A value of 9.0 implies, that the real value is more than 8.9 and less than 9.1
    • A value of 9.00000 implies, that the real value is more than 8.99999 and less than 9.00001

    Therefore, your requirement is quite unusual. That's the reason why no function exists to do what you want.

    0 讨论(0)
提交回复
热议问题