Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a decimal to the nearest fraction?

Not sure if that is the right way to ask this or not but here is the problem.

Given a latitude of 26.746346081599476, how do I find the number 26.75 as the 16th greater than the number and 26.6875 as the 16th lower than the number?

26.0
26.0625
26.125
26.1875
26.25
26.3125
26.375
26.4375
26.5
26.5625
26.625
26.6875
My Number: 26.746346081599476
26.75
26.8125
26.875
26.9375
27.0

I'm using JavaScript so an answer in that would be helpful but not necessary. I could brute force it but I'm looking for the elegant way to do it.

The bigger picture is that I want to create standard tiles for a mapping application I'm working on. We are using Bing maps and I am loading data on-demand, every time the user pans or zooms in. It would be nice to take advantage of server side caching for these requests so if I standardize the queries sent to the server I would get some cache hits. If I don't standardize the requests to the server it is highly unlikely that the same user would be viewing the exact some location at the same time.

So there is a higher chance of getting cache hits with: /path/data.json?tl=26.6875,-80.6875&br=26.75,-80.75 than with: /path/data.json?tl=26.74946187679896,-80.10930061340332&br=26.743234270702878,-80.09607195854187

Any outside the box answers are welcome as well.

like image 866
sheats Avatar asked Oct 01 '09 21:10

sheats


People also ask

What is 0.875 as a fraction?

Doing so, we find that 0.875 = 875/1000 is equivalent to 7/8.

How do you round a decimal?

Look at the digit one place to the right. If the digit is less than 5, round down. If the digit is 5 or greater, round up.

What is 7/8 as a decimal?

7 divided by 8 or 7/8 is equal to 7 divided by 8, which is equal to 0.875.

What is 0.5 rounded off to?

0.5 rounded off to the nearest whole number is 1. Since, the value after decimal is equal to 5, then the number is rounded up to the next whole number. Hence, the whole number of 0.5 will be 1.


2 Answers

To find the nearest multiples of 1/n:

lower_bound = 1.0 / n * Math.floor(n * your_number);
upper_bound = 1.0 / n * Math.ceil(n * your_number);

You may want to use some special handling if your number is already a multiple of 1/16.

// alternate solution so that lower_bound <= your_number < upper_bound
lower_bound = 1.0 / n * Math.floor(n * your_number);
upper_bound = 1.0 / n * Math.floor(n * your_number + 1.0);
like image 78
mob Avatar answered Sep 30 '22 13:09

mob


You multiply the value by 16, use the floor or ceil method, and divide by 16:

var higher = Math.ceil(number * 16) / 16;
var lower = Math.floor(number * 16) / 16;
like image 32
Guffa Avatar answered Sep 30 '22 15:09

Guffa