基于小数如何四舍五入?

huangapple go评论53阅读模式
英文:

How to round off based on decimal number?

问题

我需要将数字四舍五入。

46.38 >>> 46.40
46.40 >>> 46.40
46.41 >>> 46.50

我正在使用 round($price, 1),但这会将 46.41 转换为 46.40。但我需要 46.50

英文:

I need to round the numbers.

46.38 >>> 46.40
46.40 >>> 46.40
46.41 >>> 46.50

I am using round($price, 1) but this converts 46.41 to 46.40. But i need 46.50

答案1

得分: 3

你需要使用 ceil 而不是 round,但它不会默认提供精度。你需要自己添加这个功能,例如:

function myceil(int|float $number, int $precision, int $decimals) {
    return number_format(ceil($number*(10**$precision))/(10**$precision), 2);
}

然后可以像这样使用它:

echo myceil(46.38, 1, 2).PHP_EOL;
echo myceil(46.40, 1, 2).PHP_EOL;
echo myceil(46.41, 1, 2).PHP_EOL;

这将输出:

> 46.40 <br/>
> 46.40 <br/>
> 46.50

请注意:number_format 用于额外控制最终显示的小数位数。严格来说,它不是必需的,还会导致函数的输出是一个字符串而不是浮点数。

英文:

You need ceil instead of round, but it does not come with precision out of the box. You need to add this functionality yourself like e.g.

function myceil(int|float $number, int $precision, int $decimals) {
    return number_format(ceil($number*(10**$precision))/(10**$precision), 2);
}

You can then use it as:

echo myceil(46.38,1, 2).PHP_EOL;
echo myceil(46.40,1, 2).PHP_EOL;
echo myceil(46.41,1, 2).PHP_EOL;

This will output:
> 46.40 <br/>
> 46.40 <br/>
> 46.50

3v4l code

Note: The number_format is added to additionally control the decimals that will be shown in the end. It is not (strictly speaking) necessary and also causes the function output to be a string rather than a float.

答案2

得分: 2

我推荐这种方法:

$roundedPrice = round($price + 0.05, 1, PHP_ROUND_HALF_DOWN);

这会根据给定的输入产生所需的输出。

...或者更一般地,如果 $precision 是小数点右边的数字位数,

$roundedPrice = round($price + (1/10**$precision)/2, $precision, PHP_ROUND_HALF_DOWN);
英文:

I recommend this approach:

$roundedPrice = round($price + 0.05, 1, PHP_ROUND_HALF_DOWN);

This produces the outputs required from the inputs given.

... or more generally, if $precision is the number of digits to the right of the decimal point,

$roundedPrice = round($price + (1/10**$precision)/2, $precision, PHP_ROUND_HALF_DOWN);

huangapple
  • 本文由 发表于 2023年6月15日 17:03:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480862.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定