我的舍入不可能(Javascript和PHP)

时间:2014-05-05 16:05:09

标签: javascript php decimal precision rounding

如何使用以下逻辑舍入到2位小数? Javascrip(或jQuery)和PHP。

50.01 = 50.00 
49.99 = 50.00 
50.04 = 50.00 
49.96 = 50.00 
50.05 = 50.05
49.95 = 49.95 
50.06 = 50.10 
49.94 = 49.90 
50.09 = 50.10
49.91 = 49.90 

等...

这就像地板或天花板。使用2位小数并将第二位四舍五入。

我的PHP代码:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pruebas</title>
<script type="text/javascript">
    function verJavascript(numero){
        alert(Math.round(numero*100)/100);
    }
    verJavascript(50.01);
</script>
</head>

<body>
<?php
echo(round(50.01*100)/100);
?>
</body>

PHP或Javascript都没有向我显示&#39; 50.00&#39;

2 个答案:

答案 0 :(得分:0)

也许这个?

<?php

$num = '49.82';
$new_num = $num;

$hundredth = substr($num, -1, 1);

switch($hundredth)
{
    case '0':
        break;
    case '1':
        $new_num = ($new_num - 0.01);
        break;
    case '2':
        $new_num = ($new_num - 0.02);
        break;
    case '3':
        $new_num = ($new_num - 0.03);
        break;
    case '4':
        $new_num = ($new_num - 0.04);
        break;
    case '5':
        break;
    case '6':
        $new_num = ($new_num + 0.04);
        break;
    case '7':
        $new_num = ($new_num + 0.03);
        break;
    case '8':
        $new_num = ($new_num + 0.02);
        break;
    case '9':
        $new_num = ($new_num + 0.01);
        break;
}

echo $new_num;

?>

答案 1 :(得分:0)

尝试此功能:

round($n * 100 / 5) / 100 * 5

它会产生这些结果

50.01 = 50.00 = 50.00 
49.99 = 50.00 = 50.00 
50.04 = 50.00 = 50.05 
49.96 = 50.00 = 49.95 
50.05 = 50.05 = 50.05 
49.95 = 49.95 = 49.95 
50.06 = 50.10 = 50.05 
49.94 = 49.90 = 49.95 
50.09 = 50.10 = 50.10 
49.91 = 49.90 = 49.90 

第一列是您提出的问题,第三列是此功能的结果。

我测试了它:

function myRound($n) {
    return round($n * 100 / 5) / 100 * 5;
}

printf( "50.01 = 50.00 = %2.2f <br>", myRound(50.01) );
printf( "49.99 = 50.00 = %2.2f <br>", myRound(49.99) );
printf( "50.04 = 50.00 = %2.2f <br>", myRound(50.04) );
printf( "49.96 = 50.00 = %2.2f <br>", myRound(49.96) );
printf( "50.05 = 50.05 = %2.2f <br>", myRound(50.05) );
printf( "49.95 = 49.95 = %2.2f <br>", myRound(49.95) );
printf( "50.06 = 50.10 = %2.2f <br>", myRound(50.06) );
printf( "49.94 = 49.90 = %2.2f <br>", myRound(49.94) );
printf( "50.09 = 50.10 = %2.2f <br>", myRound(50.09) );
printf( "49.91 = 49.90 = %2.2f <br>", myRound(49.91) );