PHP show only significant (non-zero) decimals

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

    Out of the box that isn't possible because you have two different ways of treating the fragment of your floats. You'll first have to determine how many non-zero numbers there are in your fragment and then act accordingly with sprintf.

    <?php
    
    $numbers = array(
        '9.000',
        '9.100',
        '9.120',
        '9.123',
    );
    
    foreach ($numbers as $number) {
    
        $decimals = strlen(str_replace('0','', array_pop(explode('.', $number))));
        $decimals = $decimals ?: 1;
        echo $number . " => " . sprintf("%.{$decimals}f", $number);
    
        echo "<br/>";
    
    }
    
    0 讨论(0)
  • 2021-01-07 19:46

    How about

    preg_replace(/\\.$/,'.0',rtrim($value,'0'))
    
    0 讨论(0)
  • 2021-01-07 19:47

    Assuming the number is encoded as or cast to a string, here's a general purpose approach:

    $value = is_numeric($value) ? strval($value + 0) : $value;
    
    0 讨论(0)
  • 2021-01-07 19:48

    rtrim($value, "0") almost works. The problem with rtrim is that it leaves 9.000 as 9.

    So just rtrim($value, "0.") and you're done.

    0 讨论(0)
  • 2021-01-07 19:50

    Shouldn't it be?:

    $value = preg_replace('~0*$~', '', $value);
    

    The PHP preg_replace syntax is

    mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
    
    0 讨论(0)
  • 2021-01-07 19:51

    try something like this

    $number = 2.00;
    echo floor_dec($number,$deg);
    
        function floor_dec($number, $deg = null)
        {
            if ($deg == null)
                return $number * 1000 / 1000;
            else
                return $number * pow(10, $deg) / pow(10, $deg);
        }
    

    will display "2"

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