views:

591

answers:

2

In Java, how do I round to an arbitrary value? Specifically, I want to round to .0025 steps, that is:

0.032611 -> 0.0325

0.034143 -> 0.0350

0.035233 -> 0.0350

0.037777 -> 0.0375

...

Any ideas or libs?

+10  A: 
y = Math.round(x / 0.0025) * 0.0025
Zach Scrivena
I voted up, but I guess this formula doesn't handle the 2nd case, where the rouding is upwards and not downwards.
João da Silva
Thanks for the heads-up. I've changed it to Math.round().
Zach Scrivena
Works great. Thanks.
kenoa
Nice answer. Beware of overflows though...
Ran Biron
I'm worried about fp inaccuracy on this one.
Tom Hawtin - tackline
+1  A: 

You could do this:

double step = 0.0025;
double rounded = ((int)(unrounded / step + 0.5)) * step;
Ray Hidayat
i believe in java it's getting to the same problem as it gets in C++: casting to int will truncate large double values into smaller ones. 1e300 for example will become something around 2e9. consider using ceil/floor to avoid the same mess as i did today when answering a similar round question :)
Johannes Schaub - litb
Ah yes, I understand now, thank you very much!
Ray Hidayat