I realize this isn't that great of a title, so I'll try to explain more thoroughly.
Basically, I have a double that changes only by small amounts, known as clusterSize
. Then, I have a second double, a latitude or longitude on a map, known as coord
. I want to round coord
down to its nearest value that would be divisible by clusterSize
, but we haven't found any easy way to do so.
Code tried:
private double roundDown(double coord, double clusterSize) {
return clusterSize * Math.floor(coord / clusterSize);
}
And:
private double roundDown(double coord, double clusterSize) {
return Math.floor((coord + clusterSize/2) / clusterSize) * clusterSize;
}
Neither of which produced the results that I was looking for. If you could point me to a library or function that could easily accomplish this task, that would be great. Thank you!
答案 0 :(得分:1)
From my understanding, here's what you're looking for:
private double roundDown(double coord, double clusterSize) {
return coord - (coord % clusterSize);
}
Explanation:
Mod operator (a%b
) returns the remainder of a divided by b. By substracting the remainder we're guaranteeing divisibility.
Test runs:
coord clusterSize => result
1.1 .2 => 1.0
1.12 .11 => 1.1
Note: remember to properly process situations where coord < clusterSize