Markus K
Markus K

Reputation: 1653

How do I correctly round a float Android?

Why do these tests behave differently?

public void testRoundFloat() {
    final NumberFormat format = NumberFormat.getNumberInstance();
    format.setMaximumFractionDigits(2);
    format.setMinimumFractionDigits(2);
    format.setRoundingMode(RoundingMode.HALF_UP);
    assertEquals("102,345.56", format.format(102345.556f));
}

public void testRoundDouble() {
    final NumberFormat format = NumberFormat.getNumberInstance();
    format.setMaximumFractionDigits(2);
    format.setMinimumFractionDigits(2);
    format.setRoundingMode(RoundingMode.HALF_UP);
    assertEquals("102,345.56", format.format(102345.556d));
}

The first test rounding a float fails because the result of the format is xxx.55, the second test rounding a double succeeds. I am running the tests on Android 4.2.2 (level 17)

Thanks Markus

Upvotes: 3

Views: 256

Answers (2)

user2423462
user2423462

Reputation: 1

roundedNo = ( ((int)(nFloatt *100)) + 5)/100 is the easiest way to round to 2 decimal places, but there is always error in floating point math just because it is stored and calculated in base 2 and displayed in decimal.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

Java's float is the standard IEEE 32-bit floating point, which can only maintain roughly 6 decimal digits of accuracy. Your first test is failing because of roundoff representation when it converts the literal 102345.556f to internal form.

To reduce roundoff errors, use double or, for extended precision, BigDecimal.

Good reading: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Upvotes: 1

Related Questions