Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: double vs float

Tags:

In another Bruce Eckel exercise, the code I've written takes a method and changes value in another class. Here is my code:

class Big {   float b; }  public class PassObject {   static void f(Letter y) {     y.c = 'z';   } //end f()   static void g(Big z) {     z.b = 2.2;   }    public static void main(String[] args ) {     Big t = new Big();     t.b = 5.6;     System.out.println("1: t.b : " + t.b);     g(x);     System.out.println("2: t.b: " + t.b);   } //end main }//end class 

It's throwing an error saying "Possible loss of precision."

PassObject.java:13: possible loss of precision found: double required : float   z.b = 2.2 passobject.java:20: possible loss of precision found : double required : float   t.b = 5.6 

Can't doubles be floats as well?

like image 670
phill Avatar asked Apr 24 '09 19:04

phill


People also ask

Should I use double or float in Java?

Though both Java float vs Double is approximate types, use double if you need more precise and accurate results. Use float if you have memory constraint because it takes almost half as much space as double. If your numbers cannot fit in the range offered by float, then use double.

What is difference between float and double in Java?

Size: Float is of size 32 bits while double is of size 64 bits. Hence, double can handle much bigger fractional numbers than float. They differ in the allocation of bits for the representation of the number. Both float and double use 1 bit for representing the sign of the number.

Is double faster than float Java?

Performance-wise there's not likely to be much difference, and double may actually be faster. If Java is being run on a processor that doesn't have a floating-point unit at all, or supports 32-bit floats but not 64-bit floats, then a float could be faster.

Is 99.9 double or float?

Floating-point numbers are by default of type double. Therefore 99.9 is a double, not a float. What is a double data type example? Double can store numbers between the range -1.7 x 10308 to +1.7 x 10308.


2 Answers

Yes, but you have to specify that they are floats, otherwise they are treated as doubles:

z.b = 2.2f 

The 'f' at the end of the number makes it a float instead of a double.

Java won't automatically narrow a double to a float.

like image 127
mipadi Avatar answered Nov 04 '22 21:11

mipadi


No, floats can be automatically upcast to doubles, but doubles can never be floats without explicit casting because doubles have the larger range.

float range is 1.40129846432481707e-45 to 3.40282346638528860e+38

double range is 4.94065645841246544e-324d to 1.79769313486231570e+308d

like image 27
Powerlord Avatar answered Nov 04 '22 22:11

Powerlord