0

I have a double val and I'm trying to turn it to float ( cause the function I need to pass it next takes floats ) but I have failed.

I have tried to a) turn it to double and then using Float.parseFloat and b) turn it to a String.

Below is my code :

    DecimalFormat df = new DecimalFormat("#.##");
    df.setMaximumFractionDigits(2);
    df.setRoundingMode(RoundingMode.CEILING);

    Log.i(TAG, "FORMAT = " +df.format(val) );
    String valString = String.valueOf(df.format(val));
    Log.i(TAG, "valString == " + valString );
    float val2 = Float.parseFloat(valString);

but when I'm passing either the double or the String to Float.parseFloat I get back the previous float values.

Example :

FORMAT = 42.86
valString == 42.86
val== 42.857142857142854   **** why?
Mes
  • 1,671
  • 3
  • 20
  • 36
  • @ElliottFrisch but I use `Float.parseFloat(valString)` to get the float – Mes Jun 04 '16 at 20:04
  • You didn't post the `val==` part of the code... but refer to the linked question to format to 2 decimal places. – Tunaki Jun 04 '16 at 20:05
  • @Tunaki sorry for my mistake. I'll refer to the linked question, thanks – Mes Jun 04 '16 at 20:06

1 Answers1

1

Floating-point

You are using floating-point types. Floating-point is a computing approach to represent fractional numbers in such a way as to trade away accuracy for speed of calculation. The approach uses a binary representation of a decimal number, but this representation cannot match all numbers perfectly. As a result you see such anomalous extra digits in the fraction.

The string formatting is a distraction. The real issue is understanding how numbers are handled by a digital computer.

BigDecimal

When you care about accuracy use the BigDecimal class instead of a floating-point type. Much slower, but accurate.

This class can generate a float when required, but remember that not every decimal number can be represented as a float.

Usages

Example usages:

  • For money and bookkeeping, always use BigDecimal.
  • For 2D vector graphics or 3D scene rendering such as games, use floating point where speed of calculation is more important than accuracy because the extraneous extra digits in fraction can be ignored.
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154