Feb
24
|
Standard rounding provided by BigDecimal and DecimalFormat rounds to the nearest 0 or 1. If you instead want to round to 0, 1 or 0.5 then you need to do a little work
For example to round up to 4 decimal places to the nearest 0, 1, or .5 you could use the following code.
BigDecimal bd = new BigDecimal((d * 2.0) + 0.0005) .setScale(3, BigDecimal.ROUND_HALF_UP); bd = new BigDecimal(bd.doubleValue()/2.0) .setScale(4, BigDecimal.ROUND_HALF_UP); String rounded = bd.toString();
Array ( ) One Response to “How can I round a value up to nearest half?”
Leave a Reply
You must be logged in to post a comment.
May 8th, 2009 at 3:43 am
rounding to any fraction f:
double f = 0.5;
double rounded = f * Math.round(x/f);