Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't know how to cast to float in Java

Tags:

java

casting

I'm porting some code over from Processing to Java, and one issue I've come across is that processing's precompiler turns any doubles to floats. In Eclipse however, I've had to explicitly cast my values as float. Still though, I get errors that I don't understand. For instance, shouldn't putting an f at the end of this statement fix the type mismatch (Type mismatch: cannot convert from double to float)?

    springing[n] = .05*(.17*(n+1))f; 

And even on simpler statements like this I get a type mismatch. What am I doing wrong?

  float theta = .01f;
like image 569
Mike Avatar asked Feb 23 '11 01:02

Mike


1 Answers

Well, your second statement is correct by Java's standards, but in your first example Java is probably trying to prevent you from converting doubles to floats due to a loss of precision that must be explicitly asked for by the programmer, as so:

double a = //some double;
float b = (float) a;  //b will lose some of a's precision
like image 59
donnyton Avatar answered Sep 18 '22 12:09

donnyton