Why is 0.1 represented in float correctly? (I know why not as a result of 2.0-1.9)

I recently read a lot about the representation of float (including: How to represent 0.1 in arithmetic and decimal point floating point ). Now I understand that 0.1 cannot be represented correctly, and when I do this:

System.out.println(2.0f - 1.9f);

I will never get the exact result.

So the question is: As shown by 0.1f in the following code, to print 0.1 correctly? Is this some kind of syntactic sugar? The article I mentioned above says: 0.1 is represented in memory as 0.100000001490116119384765625. So why am I not getting this output for this code:

System.out.println(0.1f);

How does Java deal with this?

+5
source share
2 answers

System.out.println . Float.toString(), ( oraclew JDK) FloatingDecimal - FloatingDecimal#toJavaFormatString() .

:

BigDecimal bd = new BigDecimal(0.1f);
System.out.println(bd);

0.1f: 0.100000001490116119384765625.

+12

Float.toString(float) ( , , ):

m a? , - , , , float.

0.1f 0.1, , , float.

+5

All Articles