Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Basic question float vs double

Status
Not open for further replies.
May 13, 2002
75
GB
Quick general question, just came across a bug in my code becuase of this[surprise]:

Code:
float myf = 80f;
float result1 = myf / 100;
float result2 = myf / 100f;

Why is result1 = 0.0 and result2 = 0.8 ? I guess it's something to do with 100 being a double and 100f being a float but i don't quite understand why ? [ponder]

Cheers


Alistair [monkey]
 
Your 100 there is an int, not a double - this is a double 100.0

I'm not sure where you are getting the 0.0 from either - this class yields an output of "0.8 0.8 0.8" - which is what you would expect ...

Code:
public class Test {


	public static void main(String args[]) throws Exception {
		float m = 80.0f;

		float m1 = (m/100);

		//float m2 = (m/100.0); // won't compile as a double is returned
		double m2 = (m/100.0);

		float m3 = (m/100.0f);
		System.err.println(m1 +" " +m2 +" " +m3);

	}

}
 
Ah, ok, i think i have a casting problem...
Code:
    float f1 = 80;
    float f2 = f1 / 100;
    float f3 = 80 / 100;
    System.out.println(f1 + " " + f2 + " " + f3);

gives 80.0 0.8 0.0

80 / 100 is two ints divided and not casted automatically to floats, it should be 80f / 100f.

Cheers


Alistair [monkey]
 
Right, 80/100 is returned as an int, with truncation. Java's Strong Typing should actually give a compiler error -- but I guess they didn't bother because the float and int are both primatives.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top