116

I wrote this code:

float b = 3.6;

and I get this:

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

Why? Whats the definition of float?

james.garriss
  • 12,959
  • 7
  • 83
  • 96
t0mkaka
  • 1,843
  • 2
  • 17
  • 21
  • 4
    Possible duplicate of [Java: Why do you need to specify an 'f' in a float literal?](https://stackoverflow.com/questions/14102955/java-why-do-you-need-to-specify-an-f-in-a-float-literal) – Sneftel Jan 21 '19 at 11:23
  • 1
    @Sneftel That is not a duplicate of this question. This question asks why it doesn't compile (to which the answer is ' you must add a `f` to the literal'), while the other question asks why you must add the `f`. Although they are related, it is not a duplicate. – Mark Rotteveel Jan 21 '19 at 14:40
  • See https://meta.stackexchange.com/questions/217401/does-the-new-guidance-on-duplicate-questions-suggest-closing-a-question-as-dupli . The answers to the linked question are answers to this question. – Sneftel Jan 21 '19 at 15:15

4 Answers4

194

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.

Nicolas
  • 24,509
  • 5
  • 60
  • 66
49

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

Pang
  • 9,564
  • 146
  • 81
  • 122
jmj
  • 237,923
  • 42
  • 401
  • 438
13

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;
Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
9

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;

Carlos Sá
  • 151
  • 1
  • 5