Question

How I can Rounding to 2 decimal places with the following logic? Javascrip (or jQuery) and 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 

etc...

It would be like floor or ceill. With 2 decimals and rounding the second.

My PHP code:

<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>

Neither PHP or Javascript show me '50.00'

Was it helpful?

Solution

Maybe this?

<?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;

?>

OTHER TIPS

try this function:

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

it produce these results

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 

The two first columns are the ones you put in you question, and the third one is the result of this function.

I tested it with:

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) );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top