显示小数点后两位数字

发布于 2024-10-08 12:12:47 字数 261 浏览 4 评论 0 原文

将 PHP 字符串四舍五入到小数点后两位的正确方法是什么?

$number = "520"; // It's a string from a database

$formatted_number = round_to_2dp($number);

echo $formatted_number;

输出应为520.00

round_to_2dp() 函数应该如何定义?

What's the correct way to round a PHP string to two decimal places?

$number = "520"; // It's a string from a database

$formatted_number = round_to_2dp($number);

echo $formatted_number;

The output should be 520.00;

How should the round_to_2dp() function definition be?

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

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

发布评论

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

评论(24

勿忘心安 2024-10-15 12:12:48
bcdiv($number, 1, 2) // 2 varies for digits after the decimal point

这将精确显示小数点后两位数字。

优点:

如果您只想在浮点值后显示两位数字而不是 int,请使用此方法。

bcdiv($number, 1, 2) // 2 varies for digits after the decimal point

This will display exactly two digits after the decimal point.

Advantage:

If you want to display two digits after a float value only and not for int, then use this.

神也荒唐 2024-10-15 12:12:48
$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', ''); 

它将返回 5.98,而不对数字进行四舍五入。

$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', ''); 

It will return 5.98 without rounding the number.

预谋 2024-10-15 12:12:48

使用 PHP number_format() 函数。

Use the PHP number_format() function.

王权女流氓 2024-10-15 12:12:48

添加到其他答案,因为 number_format() 默认情况下会添加千位分隔符。

要删除它,请执行以下操作:

$number = number_format($number, 2, ".", "");

Adding to other answers, since number_format() will, by default, add thousands separator.

To remove this, do this:

$number = number_format($number, 2, ".", "");
星光不落少年眉 2024-10-15 12:12:48

对于条件舍入,即。在真正需要的地方显示小数,否则整数

123.56 => 12.56

123.00 => 123

$somenumber = 123.56;

$somenumber = round($somenumber,2);

if($somenumber == intval($somenumber))
{
    $somenumber = intval($somenumber);
}

echo $somenumber; // 123.56


$somenumber = 123.00;

$somenumber = round($somenumber,2);

if($somenumber == intval($somenumber))
{
    $somenumber = intval($somenumber);
}

echo $somenumber; // 123    

For conditional rounding off ie. show decimal where it's really needed otherwise whole number

123.56 => 12.56

123.00 => 123

$somenumber = 123.56;

$somenumber = round($somenumber,2);

if($somenumber == intval($somenumber))
{
    $somenumber = intval($somenumber);
}

echo $somenumber; // 123.56


$somenumber = 123.00;

$somenumber = round($somenumber,2);

if($somenumber == intval($somenumber))
{
    $somenumber = intval($somenumber);
}

echo $somenumber; // 123    
仅此而已 2024-10-15 12:12:48

我自己做。

$decimals = 2;
$number = 221.12345;
$number = $number * pow(10, $decimals);
$number = intval($number);
$number = $number / pow(10, $decimals);

I make my own.

$decimals = 2;
$number = 221.12345;
$number = $number * pow(10, $decimals);
$number = intval($number);
$number = $number / pow(10, $decimals);
祁梦 2024-10-15 12:12:48

round_to_2dp 是一个用户定义的函数,除非您发布该函数的声明,否则什么也做不了。

但是,我的猜测是这样做:number_format($number, 2);

round_to_2dp is a user-defined function, and nothing can be done unless you posted the declaration of that function.

However, my guess is doing this: number_format($number, 2);

佼人 2024-10-15 12:12:48
$twoDecNum = sprintf('%0.2f', round($number, 2));

舍入正确地对数字进行四舍五入,如果四舍五入后恰好只有 1 位小数,则 sprintf 会强制将其保留到 2 位小数。

$twoDecNum = sprintf('%0.2f', round($number, 2));

The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding.

少女情怀诗 2024-10-15 12:12:48
$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89

这将为您提供小数点后 2 个数字。

$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89

This will give you 2 number after decimal.

↙温凉少女 2024-10-15 12:12:48

如果你想在整个项目中使用两位小数,你可以定义:

bcscale(2);

那么下面的函数将产生你想要的结果:

$myvalue = 10.165445;
echo bcadd(0, $myvalue);
// result=10.11

但如果你不使用 bcscale 函数,你需要编写如下代码来得到你想要的结果结果。

$myvalue = 10.165445;
echo bcadd(0, $myvalue, 2);
// result=10.11

了解更多

If you want to use two decimal digits in your entire project, you can define:

bcscale(2);

Then the following function will produce your desired result:

$myvalue = 10.165445;
echo bcadd(0, $myvalue);
// result=10.11

But if you don't use the bcscale function, you need to write the code as follows to get your desired result.

$myvalue = 10.165445;
echo bcadd(0, $myvalue, 2);
// result=10.11

To know more

月依秋水 2024-10-15 12:12:48

不带圆的数字

$double = '21.188624';
echo intval($double) . '.' . substr(end(explode('.', $double)), 0, 2);

Number without round

$double = '21.188624';
echo intval($double) . '.' . substr(end(explode('.', $double)), 0, 2);
只是一片海 2024-10-15 12:12:48

这是 strtokstr_pad

$num = 520.00
strtok(round($num, 2), '.') . '.' . str_pad(strtok('.'), 2, '0')

Here's another solution with strtok and str_pad:

$num = 520.00
strtok(round($num, 2), '.') . '.' . str_pad(strtok('.'), 2, '0')
温暖的光 2024-10-15 12:12:48
  • 选择小数位数
  • 格式逗号(,)
  • 修剪尾随零的选项

一劳永逸!

function format_number($number,$dec=0,$trim=false){
  if($trim){
    $parts = explode(".",(round($number,$dec) * 1));
    $dec = isset($parts[1]) ? strlen($parts[1]) : 0;
  }
  $formatted = number_format($number,$dec); 
  return $formatted;
}

示例

echo format_number(1234.5,2,true); //returns 1,234.5
echo format_number(1234.5,2);      //returns 1,234.50
echo format_number(1234.5);        //returns 1,235
  • Choose the number of decimals
  • Format commas(,)
  • An option to trim trailing zeros

Once and for all!

function format_number($number,$dec=0,$trim=false){
  if($trim){
    $parts = explode(".",(round($number,$dec) * 1));
    $dec = isset($parts[1]) ? strlen($parts[1]) : 0;
  }
  $formatted = number_format($number,$dec); 
  return $formatted;
}

Examples

echo format_number(1234.5,2,true); //returns 1,234.5
echo format_number(1234.5,2);      //returns 1,234.50
echo format_number(1234.5);        //returns 1,235
赴月观长安 2024-10-15 12:12:48

这与我今天遇到的问题相同,想要对数字进行舍入并将浮点值返回到给定的小数位,并且它不能是字符串(从 number_format 返回)
答案是

printf('%.' . $decimalPlaces . 'f', round($number, $decimalPlaces));

感谢 mickmackusa 指出错误

That's the same question I came across today and want to round a number and return float value up to a given decimal place and it must not be string (as returned from number_format)
the answer is

printf('%.' . $decimalPlaces . 'f', round($number, $decimalPlaces));

thanks to mickmackusa for indicating the mistake

梦醒时光 2024-10-15 12:12:47

您可以使用number_format()

return number_format((float)$number, 2, '.', '');

示例:

$foo = "105";
echo number_format((float)$foo, 2, '.', '');  // Outputs -> 105.00

此函数返回一个字符串

You can use number_format():

return number_format((float)$number, 2, '.', '');

Example:

$foo = "105";
echo number_format((float)$foo, 2, '.', '');  // Outputs -> 105.00

This function returns a string.

§对你不离不弃 2024-10-15 12:12:47

使用 round() (如果您只需要浮点格式的数字,请使用,否则使用 number_format() 作为 Codemwnci 给出的答案):

echo round(520.34345, 2);   // 520.34
echo round(520.3, 2);       // 520.3
echo round(520, 2);         // 520

来自手册:

描述:

float round(float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]]);

返回 val 的舍入值到指定的精度(小数点后的位数)。 精度也可以是负数或零(默认)。

...

示例 #1 round() 示例

<?php
    echo round(3.4);         // 3
    echo round(3.5);         // 4
    echo round(3.6);         // 4
    echo round(3.6, 0);      // 4
    echo round(1.95583, 2);  // 1.96
    echo round(1241757, -3); // 1242000
    echo round(5.045, 2);    // 5.05
    echo round(5.055, 2);    // 5.06
?>

###Example #2 模式示例

<?php
    echo round(9.5, 0, PHP_ROUND_HALF_UP);   // 10
    echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
    echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
    echo round(9.5, 0, PHP_ROUND_HALF_ODD);  // 9
    echo round(8.5, 0, PHP_ROUND_HALF_UP);   // 9
    echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
    echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
    echo round(8.5, 0, PHP_ROUND_HALF_ODD);  // 9
?>

Use round() (use if you are expecting a number in float format only, else use number_format() as an answer given by Codemwnci):

echo round(520.34345, 2);   // 520.34
echo round(520.3, 2);       // 520.3
echo round(520, 2);         // 520

From the manual:

Description:

float round(float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]]);

Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

...

Example #1 round() examples

<?php
    echo round(3.4);         // 3
    echo round(3.5);         // 4
    echo round(3.6);         // 4
    echo round(3.6, 0);      // 4
    echo round(1.95583, 2);  // 1.96
    echo round(1241757, -3); // 1242000
    echo round(5.045, 2);    // 5.05
    echo round(5.055, 2);    // 5.06
?>

###Example #2 mode examples

<?php
    echo round(9.5, 0, PHP_ROUND_HALF_UP);   // 10
    echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
    echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
    echo round(9.5, 0, PHP_ROUND_HALF_ODD);  // 9
    echo round(8.5, 0, PHP_ROUND_HALF_UP);   // 9
    echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
    echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
    echo round(8.5, 0, PHP_ROUND_HALF_ODD);  // 9
?>
ぃ弥猫深巷。 2024-10-15 12:12:47

或者,

$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00

Alternatively,

$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00
噩梦成真你也成魔 2024-10-15 12:12:47

http://php.net/manual/en/function.round.php

例如

echo round(5.045, 2);    // 5.05

echo round(5.055, 2);    // 5.06

http://php.net/manual/en/function.round.php

e.g.

echo round(5.045, 2);    // 5.05

echo round(5.055, 2);    // 5.06
孤独岁月 2024-10-15 12:12:47

尝试:

$number = 1234545454; 
echo  $english_format_number = number_format($number, 2); 

输出将是:

1,234,545,454.00

Try:

$number = 1234545454; 
echo  $english_format_number = number_format($number, 2); 

The output will be:

1,234,545,454.00
深居我梦 2024-10-15 12:12:47

使用 PHP number_format() 函数。

例如,

$num = 7234545423;
echo number_format($num, 2);

输出将是:

7,234,545,423.00

Use the PHP number_format() function.

For example,

$num = 7234545423;
echo number_format($num, 2);

The output will be:

7,234,545,423.00
昔日梦未散 2024-10-15 12:12:47

使用 round(yourValue,decimalPoint) (php 手册页面< /a>) 或 number_format(yourValue,decimalPoint);

number_format() 以字符串形式返回值,例如 1,234.67 类型。因此在这种情况下您不能使用它进行加法或任何计算。如果您尝试,那么您必须处理数字格式错误...

在这种情况下,round(121222.299000000,2) 将是更好的选择。
结果将是 121222.29 ...

use round(yourValue,decimalPoint) (php manual’s page) or number_format(yourValue,decimalPoint);

number_format() return value as string like this type 1,234.67. so in this case you can not use it for addition or any calculation. if you try then you have to deal with Number Format Error...

In this case round(121222.299000000,2) will be better option.
The result would be 121222.29 ...

我家小可爱 2024-10-15 12:12:47

您可以使用 PHP printfsprintf 函数: 使用

sprintf 的示例:

$num = 2.12;
echo sprintf("%.3f", $num);

您可以在不使用 echo 的情况下运行相同的代码出色地。示例: sprintf("%.3f", $num);

输出:

2.120

或者,使用 printf

echo printf("%.2f", $num);

输出:

2.124

You can use the PHP printf or sprintf functions:

Example with sprintf:

$num = 2.12;
echo sprintf("%.3f", $num);

You can run the same without echo as well. Example: sprintf("%.3f", $num);

Output:

2.120

Alternatively, with printf:

echo printf("%.2f", $num);

Output:

2.124
忆离笙 2024-10-15 12:12:47

在这里,我使用函数在 .(点)后得到两位小数...

function truncate_number($number, $precision = 2) {

    // Zero causes issues, and no need to truncate
    if (0 == (int)$number) {
        return $number;
    }

    // Are we negative?
    $negative = $number / abs($number);

    // Cast the number to a positive to solve rounding
    $number = abs($number);

    // Calculate precision number for dividing / multiplying
    $precision = pow(10, $precision);

    // Run the math, re-applying the negative value to ensure
    // returns correctly negative / positive
    return floor( $number * $precision ) / $precision * $negative;
}

上述函数的结果:

echo truncate_number(2.56789, 1); // 2.5
echo truncate_number(2.56789);    // 2.56
echo truncate_number(2.56789, 3); // 2.567

echo truncate_number(-2.56789, 1); // -2.5
echo truncate_number(-2.56789);    // -2.56
echo truncate_number(-2.56789, 3); // -2.567

新正确答案

使用 PHP 原生 BC Math 函数 bcdiv

echo bcdiv(2.56789, 1, 1);  // 2.5
echo bcdiv(2.56789, 1, 2);  // 2.56
echo bcdiv(2.56789, 1, 3);  // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 2); // -2.56
echo bcdiv(-2.56789, 1, 3); // -2.567

Here I get two decimals after the . (dot) using a function...

function truncate_number($number, $precision = 2) {

    // Zero causes issues, and no need to truncate
    if (0 == (int)$number) {
        return $number;
    }

    // Are we negative?
    $negative = $number / abs($number);

    // Cast the number to a positive to solve rounding
    $number = abs($number);

    // Calculate precision number for dividing / multiplying
    $precision = pow(10, $precision);

    // Run the math, re-applying the negative value to ensure
    // returns correctly negative / positive
    return floor( $number * $precision ) / $precision * $negative;
}

Results from the above function:

echo truncate_number(2.56789, 1); // 2.5
echo truncate_number(2.56789);    // 2.56
echo truncate_number(2.56789, 3); // 2.567

echo truncate_number(-2.56789, 1); // -2.5
echo truncate_number(-2.56789);    // -2.56
echo truncate_number(-2.56789, 3); // -2.567

New Correct Answer

Use the PHP native BC Math function bcdiv

echo bcdiv(2.56789, 1, 1);  // 2.5
echo bcdiv(2.56789, 1, 2);  // 2.56
echo bcdiv(2.56789, 1, 3);  // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 2); // -2.56
echo bcdiv(-2.56789, 1, 3); // -2.567
忘年祭陌 2024-10-15 12:12:47

解决此问题的另一种更奇特的方法是使用 bcadd() 的 $right_operand 的虚拟值为 0

$formatted_number = bcadd($number, 0, 2);

Another more exotic way to solve this issue is to use bcadd() with a dummy value for the $right_operand of 0.

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