1

I come from Python background and taking a dive into Java world. I am trying to convert Float to int in Java. Something we do like this in Python int_var = int(float_var)

 public class p1 { public static void main(String args[]) { Integer a = new Integer(5); Float b; b = new Float(3.14); a = (int)b; System.out.println(a); } }
Yields the following error -
 p1.java:7: error: inconvertible types a = (int)b; ^ required: int found: Float 1 error 

3
  • Are you aware of primitive types and their difference with their wrapper type, i.e. int vs. Integer and float vs. Float? Why are you using wrapper types instead of primitives? You shouldn't. Commented Jul 26, 2013 at 6:53
  • Okay, guess that I got confused there. Commented Jul 26, 2013 at 6:59
  • In general, never use wrapper types unless you need an Object (to be storable in a collection, for example), or a nullable primitive. Primitive types are faster and safer. There is no reason in the code you posted to use wrapper types. Commented Jul 26, 2013 at 7:03

9 Answers 9

6

You can do it like

a = b.intValue() 
Sign up to request clarification or add additional context in comments.

Comments

5

That's one of the annoying things in Java. Fix your problem with this:

a = (int)(float)b; 

Unboxing will require that you cast from Float to float and then to int

Comments

4

Use primitives types, and you will be fine:

int a = 5; float b = 3.14f; // 3.14 is by default double. 3.14f is float. a = (int)b; 

The reason it didn't work with Wrappers is those types are non-covariant, and thus are incompatible.


And if you are using Integer types (Which you really don't need here), then you should not create Wrapper type objects using new. Just make use of auto-boxing feature:

Integer a = 5; // instead of `new Integer(5);` 

the above assignment works after Java 1.5, performing auto-boxing from int primitive to Integer wrapper. It also enables JVM to use cached Integer literals if available, thus preventing creation of unnecessary objects.

4 Comments

float b = 3.14f. What is the need for the f postfix?
Floating point literal 3.14 is by default double. For float, it's 3.14f.
To make it compile. 3.14 is a double.
thus are inconvertible ... wrappers are convertable through helper functions though
3

Since you're using boxed primitive, a = b.intValue(); should suit your needs.

2 Comments

Okay this is more pythonic!
Yeah!, What I meant is that the above code is more python like, hence pythonic
1
 float a =10.0f; int k=(int)a; 

Comments

1

Use this code
a = b.intValue();

Comments

0

Use Math.round method:-

int a = Math.round(b); 

Comments

0

for the best always use:

Math.floor(d) Math.round(d) Math.abs(d) 

These are meant for conversions.

Comments

0

You can simply use the Use Math.round() as,

 int a = Math.round(14.32f) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.