PHP 仅显示有效(非零)小数

发布于 2024-10-25 18:57:46 字数 476 浏览 1 评论 0原文

在 PHP(使用内置函数)中,我想用小数转换/格式化数字,以便仅显示非零小数。然而,我的另一个要求是,如果它是一个没有小数值的数字,我仍然想显示零。示例:

9.000 -> 9.0
9.100 -> 9.1
9.120 -> 9.12
9.123 -> 9.123

rtrim($value, "0") 几乎可以工作。 rtrim 的问题在于它将 9.000 保留为 9.sprintf() 似乎是一个候选者,但我无法让它具有可变的小数位数。 number_format() 有不同的目的,这些就是我能想到的一切...

再次,我想指出,我并不是在寻找您自制的解决方案,我'我正在寻找一种使用内部 PHP 功能来完成此任务的方法。我可以自己编写一个可以轻松完成此任务的函数,因此请保留这样的答案。

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 it's a number without a decimal value, I'd still like to show that zero. Examples:

9.000 -> 9.0
9.100 -> 9.1
9.120 -> 9.12
9.123 -> 9.123

rtrim($value, "0") almost works. The problem with rtrim is that it leaves 9.000 as 9.. sprintf() seemed like a candidate, but I couldn't get it to have a variable amount of decimals. number_format() serves a different purpose, and those were all I could come up with...

Again, I'd like to point out that I am not looking for your homemade solutions to this, I'm looking for a way to accomplish this using internal PHP functionality. I can write a function that will accomplish this easily myself, so hold answers like that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

厌味 2024-11-01 18:57:46

我认为没有办法做到这一点。正则表达式可能是您最好的解决方案:

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

演示:

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

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
撩起发的微风 2024-11-01 18:57:46

如果您想要一个内置解决方案并且您使用的 PHP 版本高于 4.2,您可以尝试 floatval( )

echo floatval(9.200);

打印

9.2

echo floatval(9.123);

打印

9.123

希望这有帮助。

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.

往日情怀 2024-11-01 18:57:46

尝试这样

$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);
    }

会显示“2”

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"

偏爱你一生 2024-11-01 18:57:46

难道不应该吗?:

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

PHP preg_replace 语法是

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

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 ]] )
绝情姑娘 2024-11-01 18:57:46

尾随零很重要:

  • 值 9.0 表示实际值大于 8.9 且小于 9.1
  • 值 9.00000 表示实际值大于 8.99999 且小于 9.00001

因此,你的要求很不寻常。这就是为什么没有函数可以做你想做的事情的原因。

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.

沉默的熊 2024-11-01 18:57:46
<?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
        );
    }
?>

输出:

9.000 -> 9.0
9.100 -> 9.1
9.120 -> 9.12
9.123 -> 9.123
<?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
吃不饱 2024-11-01 18:57:46

开箱即用是不可能的,因为您有两种不同的方式来处理浮动片段。您首先必须确定片段中有多少个非零数字,然后使用 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/>";

}

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/>";

}
塔塔猫 2024-11-01 18:57:46

怎么样

preg_replace(/\\.$/,'.0',rtrim($value,'0'))

How about

preg_replace(/\\.$/,'.0',rtrim($value,'0'))
优雅的叶子 2024-11-01 18:57:46

假设数字被编码为或转换为字符串,这是一种通用方法:

$value = is_numeric($value) ? strval($value + 0) : $value;

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;
柠檬心 2024-11-01 18:57:46

我的解决方案是让 php 将其处理为数字(即 *1),然后将其视为字符串(我的示例我使用存储为小数点后两位的百分比):

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

此输出:

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

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
街角卖回忆 2024-11-01 18:57:46

rtrim($value, "0") 几乎可以工作。 rtrim 的问题在于它将 9.000 保留为 9。

所以只需 rtrim($value, "0.") 就可以了。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文