What is float in Java?

前端 未结 4 1906
别那么骄傲
别那么骄傲 2020-12-02 07:41

I wrote this code:

float b = 3.6;

and I get this:

Error:Unresolved compilation problem: 
    Type mismatch: cannot convert from         


        
相关标签:
4条回答
  • 2020-12-02 07:57

    In Java, when you type a decimal number as 3.6, its interpreted as a double. double is a 64-bit precision IEEE 754 floating point, while floatis a 32-bit precision IEEE 754 floating point. As a float is less precise than a double, the conversion cannot be performed implicitly.

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

    For more explanation, see the primitive data types definition of the Java tutorial.

    0 讨论(0)
  • 2020-12-02 07:59

    In JAVA, values like:

    1. 8.5
    2. 3.9
    3. (and so on..)

    Is assumed as double and not float.

    You can also perform a cast in order to solve the problem:

    float b = (float) 3.5;

    Another solution:

    float b = 3.5f;

    0 讨论(0)
  • 2020-12-02 08:03

    Make it

    float b= 3.6f;
    

    A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d

    • Read More
    0 讨论(0)
  • 2020-12-02 08:04

    The thing is that decimal numbers defaults to double. And since double doesn't fit into float you have to tell explicitely you intentionally define a float. So go with:

    float b = 3.6f;
    
    0 讨论(0)
提交回复
热议问题