Bad formatting in Java decimal code format


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


before formatting, the value is 210103.6, and after formatting it should be 210.103.60, not 210.103.59.

Why am I losing 0.01?

EDIT # 1: number is an instance of the Float number class

EDIT # 2: numberOfDecimals = 2

enter image description here


source to share

3 answers

You can see the limits of precision when using float in java. Its 32-bit precision is simply not good enough for what you are using it for.

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

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

    final DecimalFormat df = new DecimalFormat("###,###,###,##0.00");


=> 210,103,59

    final DecimalFormat df = new DecimalFormat("###,###,###,##0.00");


=> 210.103,60



This is an interesting behavior Expressions tab

in eclipse. I tried to run simple code in debug mode:

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

    System.out.println( number );



With a breakpoint on line c System.out.println

and in, Expressions tab

I see exactly the same value as you, 210103.6 .



You can:

  • (throw away :)

    //,because it is already "in the format"

  • and replace it with:


because HALF_EVEN :

... sometimes known as "bankers' rounding", and is primarily used in the United States. This rounding mode is similar to the rounding policy used for float and double arithmetic in Java.



All Articles