38

Just as title says. I don't believe it is possible to do this but if it is let me know.

This is needed for a bukkit (minecraft server) plugin I'm writing. I want to take a command: tnt [power]. Where power is the string returned that I want to convert to float.

Thanks

Bobby
  • 11,419
  • 5
  • 44
  • 69
HcgRandon
  • 705
  • 2
  • 10
  • 18
  • 3
    Read the Java API for float [here](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Float.html) You can construct a new float from a string. There are also other ways to do it. Please use Google. – ubiquibacon Jan 02 '12 at 20:29

7 Answers7

106

Use Float.valueOf(String) to do the conversion.

The difference between valueOf() and parseFloat() is only the return. Use the former if you want a Float (object) and the latter if you want the float number.

Baby
  • 5,062
  • 3
  • 30
  • 52
Francis Upton IV
  • 19,322
  • 3
  • 53
  • 57
10

Using Float.parseFloat()?

class Test {
    public static void main(String[] args) {
        String s = "3.14";
        float f = Float.parseFloat(s);
        System.out.println(f);
    }
}
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1
String s = "3.14";
float f = Float.parseFloat(s);
Leo Izen
  • 4,165
  • 7
  • 37
  • 56
1

Try this:

String numberStr = "3.5";
Float number = null;
try {
   number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
    System.out.println("numberStr is not a number");
}
Wilmer
  • 1,025
  • 5
  • 9
0
public class NumberFormatExceptionExample {
private static final String str = "123.234";
public static void main(String[] args){
float i = Float.valueOf(str); //Float.parseFloat(str);
System.out.println("Value parsed :"+i);
}
}

This should resolve the problem.

Can anyone suggest how should we handle this when the string comes in 35,000.00

Gauravj
  • 21
  • 3
0

Try this:

String yourVal = "20.5";
float a = (Float.valueOf(yourVal)).floatValue(); 
System.out.println(a);
-1

The easyest way is:

///Groovy/////
String a = "23.5";
Float b = a.toFloat();

////Java////
String a = "23.5";
float b = Float.valueOf(a);