5

I've defined a method with one parameter of type float shown below:

public float getValue(float value){

    return value;
}

When I call this method by passing float value say 10.1201 shown below:

float value =  methodReturnTest.getValue(10.1201);

My IDE says to cast the argument to float. I tried searching but couldn't get the appropriate answer. so posting it. Please explain .

Thanks.

Balwant Kumar Singh
  • 1,158
  • 4
  • 24
  • 48
  • 4
    pass value as ..10.1201f..i.e. 'f' at the end..by default it takes as double – Kamlesh Arya Jan 31 '14 at 04:46
  • 2
    http://stackoverflow.com/questions/9748160/why-f-is-placed-after-float-values – RaceBase Jan 31 '14 at 04:46
  • 2
    I believe this comes down to how the compiler treats numbers. In this case you could use `10.1201f` instead, which tells the compiler to treat the value as a `float` instead of a `double` – MadProgrammer Jan 31 '14 at 04:46

4 Answers4

11

Java takes 10.1201 as double. In order to pass a float value you should append f to it like this:

float value =  methodReturnTest.getValue(10.1201f);
Vishal Santharam
  • 1,963
  • 1
  • 16
  • 30
4

In java Float Literals are specify by using f at the end otherwise it be treated as double literal.

Do like this

float value =  methodReturnTest.getValue(10.1201f);
Nambi
  • 11,944
  • 3
  • 37
  • 49
3

Float is single-precision 32-bit IEEE 754 floating point and Double is double-precision 64-bit IEEE 754 floating point. When you use a value with decimal points and if you don`t specify is as 0.23f (specifically float) java identifies it as a double.

For decimal values, double data type is generally the default choice taken by java. check this

User123456
  • 2,492
  • 3
  • 30
  • 44
2

You have to add f after a float number. If you doesn't, Java won't know if the number is supposed to be treated as a float or as a double.

float value =  methodReturnTest.getValue(10.1201f);
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73