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();
written by objects
\\ tags: BigDecimal, DecimalFormat, round, rounding
Decimal format uses BigDecimal.ROUND_HALF_EVEN and prior to 1.6 this cannot be changed.
In 1.6 a setRoundingMethod() was added to allow the rounding strategy to be changed.
DecimalFormat df = NumberFormat.getNumberInstance();
df.setRoundingMode(1, RoundingMode.HALF_UP);
String formatted = df.format(12.345);
If you need an alternate rounding strategy prior to 1.6 then you need to use BigDecimal to do your formatting.
double d = 123.45;
BigDecimal bd = new BigDecimal(d);
bd.setScale(1, BigDecimal.ROUND_HALF_UP);
String formatted = bd.toString();
written by objects
\\ tags: BigDecimal, conversion, DecimalFormat, format, rounding
Use the compareTo() method instead of the equals() method.
equals() only considers two BigDecimal’s to be equal if they have same value and scale (eg. 1.25 is not equal to 1.250 when using equals() method).
BigDecimal a = new BigDecimal("1.25");
BigDecimal b = new BigDecimal("1.250");
if (a.compareTo(b)==0)
{
System.out.println("They are equal");
}
written by objects
\\ tags: BigDecimal, compareTo, equals
Recent Comments