What is a float in Java?

I wrote this code:

float b = 3.6; 

and I get the following:

 Error: Unresolved compilation problem: 
     Type mismatch: cannot convert from double to float

Why? What is the definition of float ?

+79
java floating-point
Feb 22 '11 at 10:05
source share
4 answers

In Java, when you enter a decimal number as 3.6 , it is interpreted as double . double is the 64-bit precision of the IEEE 754 floating point, and float is the 32-bit precision of the IEEE 754 floating point. Since a float less accurate than a double , the conversion cannot be performed implicitly.

If you want to create a float, you must end your number with f (i.e.: 3.6f ).

See the Java Tutorial Primitive Data Type Definition for more details.

+160
Feb 22 '11 at 10:15
source share

Do this

 float b= 3.6f; 

A floating-point literal is of type float if the letter ASCII F or f is added to it; otherwise, its type is double and you can add the suffix of the ASCII letter D or d to it.

+37
Feb 22 2018-11-22T00:
source share

The fact is that decimal numbers double by default. And since double does not fit into a float, you should directly say that you intentionally define a float. So go with:

 float b = 3.6f; 
+13
Feb 22 '11 at 10:09
source share

In JAVA, values ​​such as:

  • 8.5
  • 3.9
  • (etc.)

It is assumed that double , not float .

You can also do a roll to solve the problem:

float b = (float) 3.5 ;

Another solution:

float b = 3.5f ;

+6
May 19 '15 at 17:02
source share



All Articles