round() 模式 ROUND_HALF_DOWN 与 PHP 5.2.17 [英] round() mode ROUND_HALF_DOWN with PHP 5.2.17

查看:76
本文介绍了round() 模式 ROUND_HALF_DOWN 与 PHP 5.2.17的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 PHP 5.2.17 中模拟 ROUND_HALF_DOWN 模式 - 我无法升级服务器的 PHP 版本.任何想法如何实现这一目标?

I need to simulate ROUND_HALF_DOWN mode in PHP 5.2.17 - I cannot upgrade the server's PHP version. Any ideas how to achieve this?

基本思想是 1.895 变成 1.89,而不是像通常使用 round() 那样的 1.90.

The basic idea is that 1.895 becomes 1.89, not 1.90 like it usually does with round().

这个函数似乎可以解决问题:

This function seems to do the trick:

function nav_round($v, $prec = 2) {
    // Seems to fix a bug with the ceil function
    $v = explode('.',$v);
    $v = implode('.',$v);
    // The actual calculation
    $v = $v * pow(10,$prec) - 0.5;
    $a = ceil($v) * pow(10,-$prec);
    return number_format( $a, 2, '.', '' );
}

推荐答案

你可以去掉 0.5^p 其中 p 是精度,然后使用天花板:

You can take off 0.5^p where p is the precision and then use ceiling:

<?php

function round_half_down($v, $prec) {
  $v = $v * pow(10,$prec) - 0.5;
  return ceil($v) * pow(10,-$prec);
}


print round_half_down(9.5,0) . "\n";
print round_half_down(9.05,0) . "\n";
print round_half_down(9.051,0) . "\n";
print round_half_down(9.05,1) . "\n";
print round_half_down(9.051,1) . "\n";
print round_half_down(9.055,2) . "\n";
print round_half_down(1.896,2) . "\n";

?>

产量:

$ php test.php 
9
9
9
9
9.1
9.05
1.9

你会注意到,对于任何数 x <= p <= x.5,我们得到天花板(p - 0.5) = x,并且对于所有 x+1 => p > x.5,我们得到天花板(p - 0.5)= x+1.这应该正是您想要的.

You'll note that for any number x <= p <= x.5, we get ceiling(p - 0.5) = x, and for all x+1 => p > x.5, we get ceiling(p - 0.5) = x+1. This should be exactly what you want.

这篇关于round() 模式 ROUND_HALF_DOWN 与 PHP 5.2.17的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆