PHP number_format 是否四舍五入?

发布于 2024-11-09 03:49:34 字数 199 浏览 4 评论 0原文

我的价格是“0,10”或“00000,10”,

现在当我尝试时

number_format($price, 2, ',', '')

,我得到 0,00。 我该如何解决这个问题?我想要 0.10 美元。 我不想四舍五入。

或者当我有 5,678 时,我得到 5,68。但我想要5,67。

I have a price "0,10" or "00000,10"

Now when i try

number_format($price, 2, ',', '')

I get 0,00.
How can i fix this? I want 0,10 $.
I don't want rounding.

Or when i have 5,678, i get 5,68. But i want 5,67.

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

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

发布评论

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

评论(10

药祭#氼 2024-11-16 03:49:34

有几个人提到将其四舍五入为 3,然后删除最后一个字符。这实际上是行不通的。假设您有 2.9999,将其四舍五入为 3,即为 3.000。

这仍然不准确,最好的解决方案是这样的:

$price = '5.678';
$dec = 2;
$price = number_format(floor($price*pow(10,$dec))/pow(10,$dec),$dec);

它的作用是将价格乘以 100(10^小数),得到 567.8,然后我们使用下限将其得到 567,然后将其除以100 得到 5.67

Several people have mentioned rounding it to 3 and then dropping the last character. This actually does not work. Say you have 2.9999 and round it to 3 it's 3.000.

This is still not accurate, the best solution is this:

$price = '5.678';
$dec = 2;
$price = number_format(floor($price*pow(10,$dec))/pow(10,$dec),$dec);

What this does is takes the price and multiplies it by 100 (10^decimal) which gives 567.8, then we use floor to get it to 567, and then we divide it back by 100 to get 5.67

花开雨落又逢春i 2024-11-16 03:49:34

您可以在使用 floor 向下舍入之前增加数字的大小:

$price = floor($price * 100) / 100;
$formatted = number_format($price, 2, ',', '');

另一种解决方案,这可能会提供更好的精度,因为它避免了浮点运算,就是将其格式化为三位小数,并在格式化后丢弃最后一位数字:

$formatted = substr(number_format($price, 3, ',', ''), 0, -1);

You can increase the size of the number before rounding down with floor:

$price = floor($price * 100) / 100;
$formatted = number_format($price, 2, ',', '');

Another solution, which may give better precision since it avoids floating-point arithmetic, is to format it with three decimals and throw away the last digit after formatting:

$formatted = substr(number_format($price, 3, ',', ''), 0, -1);
打小就很酷 2024-11-16 03:49:34

您应该在使用 str_replace 之前将逗号填充的数字转换回正常的十进制。
$number = str_replace(",", ".", $number);
然后你可以使用 number_format

you should convert comma-filled number back to normal decimal before with str_replace.
$number = str_replace(",", ".", $number);
and then you can use number_format

陌上青苔 2024-11-16 03:49:34

“00000,10”是一个字符串。你应该有小数点。为了获得所需的行为,您可以使用:

echo substr(number_format(str_replace(',', '.', $price), 3, ',', ''), 0, -1);

"00000,10" is a string. You should a decimal point. To get the desired behaviour, you could use:

echo substr(number_format(str_replace(',', '.', $price), 3, ',', ''), 0, -1);
偷得浮生 2024-11-16 03:49:34

使用这个(需要激活 intl PHP 扩展)

$numberFmtCurrency = new NumberFormatter('de_AT', NumberFormatter::CURRENCY);
$numberFmtCurrency->setAttribute(NumberFormatter::ROUNDING_INCREMENT, 0);
$numberFmtCurrency->formatCurrency(328.13, 'EUR'); // prints € 328.13 (and not 328.15)

Use this (needs activated intl PHP extension)

$numberFmtCurrency = new NumberFormatter('de_AT', NumberFormatter::CURRENCY);
$numberFmtCurrency->setAttribute(NumberFormatter::ROUNDING_INCREMENT, 0);
$numberFmtCurrency->formatCurrency(328.13, 'EUR'); // prints € 328.13 (and not 328.15)
叹梦 2024-11-16 03:49:34

如果您实际上只是想清除前导零并限制长度,而不是四舍五入到一定数量的小数位,则更通用的解决方案可能是此函数:

    function cutafter($string,$cutpoint,$length)
    {
        $temp = explode($cutpoint,$string);
        $int = $temp[0];
        $sub = $temp[1];
        return number_format($int,0).','.substr($sub,0,$length);
    }

示例:

    $number = "005,678";
    $answer = cutafter($number,",",2);

$answer 现在等于“5,67”

If you are literally just wanting to clear leading zeroes and just limit the length, rather than round to a certain amount of decimal places, a more generalised solution could be this function:

    function cutafter($string,$cutpoint,$length)
    {
        $temp = explode($cutpoint,$string);
        $int = $temp[0];
        $sub = $temp[1];
        return number_format($int,0).','.substr($sub,0,$length);
    }

Example:

    $number = "005,678";
    $answer = cutafter($number,",",2);

$answer now equals "5,67"

过气美图社 2024-11-16 03:49:34

在执行 number_format 之前,字符串“0,10”被 php 转换为数字。因为 php 总是使用英语表示法,所以它不会处理逗号。

echo "4 apples" + 2;  
output: 6

“apples”部分被忽略,就像您的“,10”被忽略一样。

将“,”转换为“.”允许 php 查看其他数字。

$price = str_replace(',', '.', '0,10');
number_format($price, 2, ',', '');

Just before number_format is executed the string "0,10" is converted by php to an number. because php always uses the engish notation the it won't look after the comma.

echo "4 apples" + 2;  
output: 6

The " apples" part is ignored just as your ",10" is ignored.

Converting the "," to a "." allows php to see the other digits.

$price = str_replace(',', '.', '0,10');
number_format($price, 2, ',', '');
那支青花 2024-11-16 03:49:34

我的问题是 html 验证器错误消息 number_format() 参数不是双重的。

我通过为该参数放置 floatval 来解决此错误消息,例如 number_format(floatval($var),2,'.',' ') ,效果很好。

My problem was that html validator error messege thar number_format() argument is not double.

I solved this error message by placing floatval for that argument like number_format(floatval($var),2,'.',' ') and that is working good.

梦一生花开无言 2024-11-16 03:49:34
function format_numeric($value) {

    if (is_numeric($value)) { // is number

        if (strstr($value, ".")) { // is decimal

            $tmp = explode(".", $value);
            $int = empty($tmp[0]) ? '0' : $tmp[0];
            $dec = $tmp[1];
            $value = number_format($int, 0) . "." . $dec;
            return $value;
        }

        $value =  number_format($value);
        return $value;
    }

    return $value; // is string
}

Unit Testing:

Passed / 1100000 => 1,100,000
Passed / ".9987" => .9987
Passed / 1100.22 => 1,100.22
Passed / 0.9987 => 0.9987
Passed / .9987 => 0.9987
Passed / 11 => 11
Passed / 11.1 => 11.1
Passed / 11.1111 => 11.1111
Passed / "abc" => "abc" 
function format_numeric($value) {

    if (is_numeric($value)) { // is number

        if (strstr($value, ".")) { // is decimal

            $tmp = explode(".", $value);
            $int = empty($tmp[0]) ? '0' : $tmp[0];
            $dec = $tmp[1];
            $value = number_format($int, 0) . "." . $dec;
            return $value;
        }

        $value =  number_format($value);
        return $value;
    }

    return $value; // is string
}

Unit Testing:

Passed / 1100000 => 1,100,000
Passed / ".9987" => .9987
Passed / 1100.22 => 1,100.22
Passed / 0.9987 => 0.9987
Passed / .9987 => 0.9987
Passed / 11 => 11
Passed / 11.1 => 11.1
Passed / 11.1111 => 11.1111
Passed / "abc" => "abc" 
天赋异禀 2024-11-16 03:49:34

请参阅此答案了解更多细节。

function numberFormat($number, $decimals = 0, $decPoint = '.' , $thousandsSep = ',')
{
    $negation = ($number < 0) ? (-1) : 1;
    $coefficient = pow(10, $decimals);
    $number = $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
    return number_format($number, $decimals, $decPoint, $thousandsSep);
}

See this answer for more details.

function numberFormat($number, $decimals = 0, $decPoint = '.' , $thousandsSep = ',')
{
    $negation = ($number < 0) ? (-1) : 1;
    $coefficient = pow(10, $decimals);
    $number = $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
    return number_format($number, $decimals, $decPoint, $thousandsSep);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文