Solved

# How can I round a double to the nearest 0.5 or 0.25 ?

Posted on 2004-08-02
1,103 Views
Hi, how can I round a double to the nearest 0.5 or 0.25 ?

e.g.

rounding to nearest 0.25:

4.08 -> 4
4.19 -> 4.25
5.55 -> 5.50
6.78 -> 6.75
6.98 -> 7

rounding to nearest 0.50:

4.08 -> 4
4.19 -> 4
5.55 -> 5.50
6.78 -> 7
6.98 -> 7
0
Question by:ycomp
• 4
• 2

LVL 37

Expert Comment

ID: 11697123
return Math.ceil( val * 0.25d ) / 0.25f ;
and
return Math.ceil( val * 0.5d ) / 0.5f ;
0

LVL 37

Expert Comment

ID: 11697166
Stupid me. That's wrong sorry.
0

LVL 86

Accepted Solution

CEHJ earned 500 total points
ID: 11697225
double x = (double)(Math.round(d * 4.0)) / 4;
0

LVL 86

Assisted Solution

CEHJ earned 500 total points
ID: 11697237
(that's for nearest .25) - change to 2.0 for nearest .5
0

LVL 86

Expert Comment

ID: 11697255
... and of course 'd' is the original value
0

Author Comment

ID: 11697273
thanks CEHJ
0

LVL 86

Expert Comment

ID: 11697328
:-)
0

## Featured Post

### Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
The viewer will learn how to implement Singleton Design Pattern in Java.