3

Code is:

private static DecimalFormat amDF=new DecimalFormat("###,###,###,##0.00");
amDF.setDecimalFormatSymbols(dfs); <- this only sets decimal separator, it works fine
amDF.setMinimumFractionDigits(2);
amDF.setMaximumFractionDigits(2);

before formating value is 210103.6 and after formatting it should be like: 210.103,60, not 210.103,59.

Why do i lose 0.01 ?

EDIT #1: number is instance of class Float number

EDIT #2: numberOfDecimals = 2

enter image description here

anotherUser
  • 551
  • 6
  • 29

2 Answers2

1

You are seeing the limits of precision when using a float in java. Its 32 bit precision is simply not sufficient for what you are using it for.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead.

You can demonstrate the problem by changing the type of your number to a double. In that case your DecimalFormat.format() outputs the correct value because double has enough precision to hold the number you are working with.

    final DecimalFormat df = new DecimalFormat("###,###,###,##0.00");
    df.setMinimumFractionDigits(2);
    df.setMaximumFractionDigits(2);
    System.out.println(df.format(210103.6f));

=> 210.103,59

    final DecimalFormat df = new DecimalFormat("###,###,###,##0.00");
    df.setMinimumFractionDigits(2);
    df.setMaximumFractionDigits(2);
    System.out.println(df.format(210103.6d));

=> 210.103,60

sheltem
  • 3,754
  • 1
  • 34
  • 39
  • Yes, this is correct answer i agree after reading some text about float. As said "This data type should never be used for precise values, such as currency". But the eclipse output actually in debug mode is wrong, thats why i was confused. – anotherUser Apr 22 '15 at 13:07
0

this is interesting behavior of Expressions tab in eclipse I tried to run in debug mode simple code:

public static void main( String[] args ) throws Exception
{
    float number = 210103.59f;

    System.out.println( number );

}

With break point on line with System.out.println and in Expressions tab I see exactly this same value as you that is 210103.6.

Mateusz Sroka
  • 2,255
  • 2
  • 17
  • 19