Question:
How can I convert a String type value to an integer or float?For example,
I’ve tried it like this:String str=”155.230″;float real;real = str.HowCanIConvert???????;
But this method doesn’t always work.What’s the problem?Integer aValue = new Integer(String.valueOf(“1”));
Answer:
You’re lucky your solution worked at all! Probably, themethod:
was being called, as I see no variant ofpublic static String valueOf(Object obj)
String.valueOf()
that expects a String parameter.Perhaps you intended
Of course this only returns anInteger.valueOf(“1”);
Integer
. To get an int
, you’llneed to compose it with another conversion:Forint i = intValue(Integer.valueOf(“1”));
floats
, you need to first convert to a Float
, thenconvert to a float
:Java also provide afloat f = floatValue(Float.valueOf(“155.230”));
parseInt
method. Try this:int i = Integer.parseInt(“1”);