How to reset a variable of type float

My code works if my float variable is set to 0, but I want my code to work if my variable is zero. How could I do this? Here is a snippet of code that I wrote:

float oikonomia= (float)((float)new Float(vprosvasis7.getText().toString())); if(oikonomia==0){ 

I bound if(oikonomia==null) or if(oikonomia=null) , but it does not work.

PS: Another way would be to initially set oikonomia=0; , and if users change it, go to my if session. This also does not work.

Float oikonomia = Float.valueOf (vprosvasis7.getText (). ToString ());

  if(oikonomia.toString() == " "){ float oikonomia= (float)((float)new Float(vprosvasis7.getText().toString())); oikonomia=0; if(oikonomia==0){ 

this method doesn't work either:

 Float oikonomia = Float.valueOf(vprosvasis7.getText().toString()); if(oikonomia.toString() == " "){ 
+6
java android
source share
4 answers

If you want to have a NULL float, try Float instead of Float

 Float oikonomia= new Float(vprosvasis7.getText().toString()); 

But it will never be null in the same way as in your example ...

EDIT : Ahhh, I'm starting to understand what the problem is. You really don't know what vprosvasis7 contains, and whether it is correctly initialized as a number. So try this, then:

 Float oikonomia = null; try { oikonomia = new Float(vprosvasis7.getText().toString()); } catch (Exception ignore) { // We're ignoring potential exceptions for the example. // Cleaner solutions would treat NumberFormatException // and NullPointerExceptions here } // This happens when we had an exception before if (oikonomia == null) { // [...] } // This happens when the above float was correctly parsed else { // [...] } 

Of course, there are many ways to simplify the above code and write cleaner code. But I think this should explain how you should parse String in Float correctly and safely without using any exceptions ...

+14
source share

Floats and floats are not the same thing. The "float" type in Java is a primitive type that cannot be null.

+3
source share

You should probably do something like this

Float oikonomia = Float.valueOf (vprosvasis7.getText (). ToString ());

You will get a NumberFormatException if you try to parse a string that does not translate into a real number. That way, you can simply wrap this statement in a catch try block and handle the error correctly.

Hope this helps.

+1
source share

try the following:

 Float oikonomia = null; try{ oikonomia = Float.valueOf(vprosvasis7.getText().toString()); }catch(numberFormatException e){ // logging goes here } 

Now the value is NULL in the case of an invalid (non float) string.

0
source share

All Articles