php 删除两个小数点后的数字,而不对值进行四舍五入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9944001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:57:24  来源:igfitidea点击:

Delete digits after two decimal points, without rounding the value

phpfunctionrounding

提问by air

i have value in php variable like that

我在 php 变量中有这样的值

$var='2.500000550';
echo $var

what i want is to delete all decimal points after 2 digits.

我想要的是删除 2 位数字后的所有小数点。

like now value of variable will be

就像现在变量的值将是

$var='2.50';
echo $var

keep in mind this value is coming from mysql databse

请记住此值来自 mysql 数据库

but when i use round php functioni got round but i dont need round, i just need to delete all digits after 2 decimal simple.

但是当我使用时,round php function我得到了圆但我不需要圆,我只需要简单地删除 2 个小数点后的所有数字。

i have tired, flot()and lot of other option no success.

我累了,flot()很多其他选择都没有成功。

Thanks

谢谢

回答by random_user_name

TL;DR:

特尔;博士:

The PHP native function bcdivseems to do precisely what is required, and properly.

PHP 本机函数bcdiv似乎完全正确地完成了所需的工作。

To simply "truncate" a number, bcdiv($var, 1, 2);where 2 is the number of decimals to preserve (and 1 is the denomenator - dividing the number by 1 allows you to simply truncate the original number to the desired decimal places)

简单地“截断”一个数字,bcdiv($var, 1, 2);其中 2 是要保留的小数位数(1 是分母 - 将数字除以 1 允许您简单地将原始数字截断到所需的小数位)

Full Answer (for history)

完整答案(历史)

This turns out to be more elusive than one might think.

事实证明,这比人们想象的更难以捉摸。

After this answer was (incorrectly) upvoted quite a bit, it has come to my attention that even sprintf will round.

在这个答案(错误地)得到了相当多的支持后,我注意到即使是 sprintf 也会四舍五入。

Rather than delete this answer, I'm turning it into a more robust explanation / discussion of each proposed solution.

我没有删除这个答案,而是将它变成对每个提议的解决方案的更可靠的解释/讨论。

number_format - Incorrect. (rounds)
Try using number format:

number_format - 不正确。(轮)
尝试使用数字格式

$var = number_format($var, 2, '.', '');  // Last two parameters are optional
echo $var;
// Outputs 2.50

If you want it to be a number, then simply type-cast to a float:

如果你希望它是一个数字,那么只需将类型转换为浮点数:

$var = (float)number_format($var, 2, '.', '');

Note:as has been pointed out in the comments, this does in fact roundthe number.

注意:正如评论中指出的那样,这实际上是对数字进行四舍五入

sprintf - incorrect. (sprintf also rounds)
If not rounding the number is important, then per the answer below, use sprintf:

sprintf - 不正确。( sprintf 也
舍入如果不舍入数字很重要,那么根据下面的答案,使用sprintf

$var = sprintf("%01.2f", $var);

floor - not quite! (floor rounds negative numbers)

地板 - 不完全!(地板四舍五入负数)

floor, with some math, will come close to doing what you want:

floor,通过一些数学运算,将接近做你想做的事:

floor(2.56789 * 100) / 100; // 2.56

Where 100 represents the precision you want. If you wanted it to three digits, then:

其中 100 代表您想要的精度。如果你想要三位数,那么:

floor(2.56789 * 1000) / 1000; // 2.567

However, this has a problem with negative numbers. Negative numbers still get rounded, rather than truncated:

但是,这有负数的问题。负数仍然被四舍五入,而不是被截断:

floor(-2.56789 * 100) / 100; // -2.57

"Old" Correct answer: function utilizing floor

“旧” 正确答案:利用楼层的功能

So a fully robust solution requires 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

回答by Sujit Agarwal

floor(2.500000550 * 100) / 100;

This should do your task...

这应该可以完成你的任务......

回答by flu

You're requesting a function that returns "2.50"and not 2.5, so you aren't talking about arithmetichere but string manipulation. Then preg_replaceis your friend:

您正在请求一个返回"2.50"而不是返回的函数2.5,因此您在这里谈论的不是算术而是字符串操作。然后preg_replace是你的朋友:

$truncatedVar = preg_replace('/\.(\d{2}).*/', '.', $var);

// "2.500000050" -> "2.50", "2.509" -> "2.50", "-2.509" -> "2.50", "2.5" -> "2.5"

If you want to do it with arithmetic, simply use:

如果你想用算术来做,只需使用:

$truncatedVar = round($var * 100) / 100);

// "2.500000050" -> "2.5", "2.599" -> "2.59", "-2.599" -> "2.59"

回答by matino

try with number_format:

尝试使用number_format

echo number_format('2.50000050', 2); // 2.50

回答by Liphtier

number_format rounds the number

number_format 舍入数字

php > echo number_format(128.20512820513, 2)."\n";
128.21

I used preg_replace to really cut the string

我用 preg_replace 来真正切断字符串

php > echo preg_replace('/(\.\d\d).*/', '', 128.20512820513)."\n";
128.20

回答by David Constantine

someone posted here about

有人在这里发布了关于

floor(2.500000550 * 100) / 100;

楼层(2.500000550 * 100) / 100;

function cutAfterDot($number, $afterDot = 2){
$a = $number * pow(10, $afterDot);
$b = floor($a);
$c = pow(10, $afterDot);
echo "a $a, b $b, c $c<br/>";
return $b/$c ;
}
echo cutAfterDot(2.05,2);

a 205, b 204, c 100
2.04

so in raw form don't use it... But if you add a little epsilon...

所以在原始形式中不要使用它......但是如果你添加一点epsilon......

function cutAfterDot($number, $afterDot = 2){
        return floor($number * pow(10, $afterDot) + 0.00001) / pow(10, $afterDot);
    }

it works!

有用!

回答by Aurimas Li?kus

use sprintf

使用sprintf

sprintf("%01.2f", $var);

回答by Faisal

Use the PHP native function bcdiv.

使用 PHP 原生函数bcdiv

Example:

例子:

echo bcdiv(3.22871, 1, 1);  // 3.2
echo bcdiv(3.22871, 1, 2);  // 3.22
echo bcdiv(3.22871, 1, 3);  // 3.228
echo bcdiv(-3.22871, 1, 1); // -3.2
echo bcdiv(-3.22871, 1, 2); // -3.22

For your case:

对于您的情况:

$var='2.500000550';
echo $var
echo bcdiv($var, 1, 2);  // 2.50

回答by Sujjad A

$num = 118.74999669307;
$cut = substr($num, 0, ((strpos($num, '.')+1)+2));
// Cut the string from first character to a length of 2 past the decimal.
// substr(cut what, start, ( (find position of decimal)+decimal itself)+spaces after decimal) )
echo $cut; 

回答by Jon C.

floor - not quite! (floor rounds negative numbers)

地板 - 不完全!(地板四舍五入负数)

A possible solution from cale_banswer.

来自cal_b答案的可能解决方案。

static public function rateFloor($rate, $decimals)
{

    $div = "1" . str_repeat("0", $decimals);

    if ($rate > 0) {
        return floor($rate * $div) / $div;
    }

    $return = floor(abs($rate) * $div) / $div;

    return -($return);

}


static public function rateCeil($rate, $decimals)
{

    $div = "1" . str_repeat("0", $decimals);

    if ($rate > 0) {
        return ceil($rate * $div) / $div;
    }

    $return = ceil(abs($rate) * $div) / $div;

    return -($return);

}

Positive

积极的

Rate: 0.00302471

Floor: 0.00302400

Ceil: 0.00302500

比率:0.00302471

楼层:0.00302400

天花板:0.00302500

Negative

消极的

Rate: -0.00302471

Floor: -0.00302400

Ceil: -0.00302500

比率:-0.00302471

楼层:-0.00302400

上限:-0.00302500