Bad formatting in Java decimal code format

Code:

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 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

+3


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.

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

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");
    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

+1


source


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 .

0


source


You can:

  • (throw away :)

    amDF.setMinimumFractionDigits(2);
    amDF.setMaximumFractionDigits(2);
    //,because it is already "in the format"
    
          

  • and replace it with:

    amDF.setRoundingMode(java.math.RoundingMode.UP);
    
          

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.

0


source







All Articles