Question

I have a number that I want to look up in my database. The database intervals are like this:

0,78
0,82
0,86
0,90
0,94
0,98
1,02
1,06
1,10
1,14

So the number is added with 0.04 all the time.

The numbers I want to look up is like this:

0,77778
0.91666 
1,14286
1,50000
1,76923

How can I round it to the nearest 0.04 ?

So they would look like this:

0,78
0.90 
1,14
1,50
1,78
Was it helpful?

Solution

If you need to make it to the nearest multiple of 0.04 here is a function that does the job:

function round_to_0_04($round)
{
    $int_val = round($round * 100);
    $rest = $int_val % 4;
    $rounded_val = $int_val - $rest;
    return $rounded_val /100;
}

If the number needs to be uneven (starting from 0.02 instead of 0), you should use it as follows:

$number = ...;
round_to_0_04($number - 0.02) + 0.02;

Or just modify the function as follows:

function round_to_0_04_uneven($round)
{
    $round -= 0.02;
    $int_val = round($round * 100);
    $rest = $int_val % 4;
    $rounded_val = $int_val - $rest;
    return $rounded_val /100 + 0.02;
}

OTHER TIPS

Use round and a bit of math.

round(($number-0.02)/0.04)*0.04+0.02

or this if 0.02 shift is mistake

round($number/0.04)*0.04
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top