简体   繁体   English

显示一个数字到小数点后两位

[英]Show a number to two decimal places

What's the correct way to round a PHP string to two decimal places?将 PHP 字符串舍入到小数点后两位的正确方法是什么?

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

$formatted_number = round_to_2dp($number);

echo $formatted_number;

The output should be 520.00 ; output 应该是520.00

How should the round_to_2dp() function definition be? round_to_2dp() function 定义应该如何?

You can use number_format() :您可以使用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 .此函数返回一个字符串

Use round() (use if you are expecting a number in float format only, else use number_format() as an answer given by Codemwnci ):使用round() (如果您只需要浮点格式的数字,请使用,否则使用 number_format() 作为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).val的舍入值返回到指定precision (小数点后的位数)。 precision can also be negative or zero (default). precision也可以是负数或零(默认)。

... ...

Example #1 round() examples Example #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 mode examples 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 ?>

或者,

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

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

eg例如

echo round(5.045, 2);    // 5.05

echo round(5.055, 2);    // 5.06

Try:尝试:

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

The output will be:输出将是:

1,234,545,454.00

You can use the PHP printf or sprintf functions:您可以使用 PHP printfsprintf函数:

Example with sprintf : sprintf示例:

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

You can run the same without echo as well.您也可以在没有echo的情况下运行相同的程序。 Example: sprintf("%.3f", $num);示例: sprintf("%.3f", $num);

Output:输出:

2.120

Alternatively, with printf :或者,使用printf

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

Output:输出:

2.124

Use the PHP number_format() function.使用 PHP number_format()函数。

For example,例如,

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

The output will be:输出将是:

7,234,545,423.00

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

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

It will return 5.98 without rounding the number.它将返回 5.98 而不舍入数字。

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.如果您只想在浮点值后显示两位数字而不是 int,请使用它。

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 function bcdiv使用 PHP 原生函数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

使用 PHP number_format()函数。

For conditional rounding off ie.对于条件四舍五入即。 show decimal where it's really needed otherwise whole number在真正需要的地方显示小数,否则为整数

123.56 => 12.56 123.56 => 12.56

123.00 => 123 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    

I make my own.我自己做。

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

round_to_2dp is a user-defined function, and nothing can be done unless you posted the declaration of that function. round_to_2dp是用户定义的函数,除非您发布该函数的声明,否则无法执行任何操作。

However, my guess is doing this: number_format($number, 2);但是,我的猜测是这样做: number_format($number, 2);

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

舍入正确地舍入数字,如果舍入后恰好只有 1 个小数位,sprintf 会强制它保留 2 个小数位。

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.但是如果不使用 bcscale 函数,则需要编写如下代码才能得到想要的结果。

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

To know more了解更多

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

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

use roud(yourValue,decimalPoint) or number_format(yourValue,decimalPoint);使用roud(yourValue,decimalPoint)number_format(yourValue,decimalPoint);

number_format() return value as string like this type 1,234.67 . number_format()以字符串形式返回值,例如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.在这种情况下, round(121222.299000000,2)将是更好的选择。 The result would be 121222.29 ...结果将是121222.29 ...

Number without round无圆数

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

Adding to other answers, since number_format() will, by default, add thousands separator.添加到其他答案中,因为 number_format() 默认情况下会添加千位分隔符。

To remove this, do this:要删除它,请执行以下操作:

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

Here's another solution with strtok and str_pad :这是strtokstr_pad的另一个解决方案:

$num = 520.00
strtok(round($num, 2), '.') . '.' . str_pad(strtok('.'), 2, '0')
  • 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

如果你像我一样使用math equation你可以这样设置:

{math equation="x + y" x=4.4444 y=5.0000 format="%.2f"}

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

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

You can use PHP round() function. 您可以使用PHP round()函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM