0

Is there any Java method that equivalents to php floatval?

If not, how can I get float value of a string in Java?

4 Answers 4

7
float f = Float.parseFloat("25");
String s = Float.toString(25.0f);

System.out.printf("%f", Float.parseFloat("1.0E7")); outputs 10000000.000000

See http://ideone.com/3o6dO

updated from natasha answer

use regex

    Pattern p = Pattern.compile("([-+]?[0-9]*\\.?[0-9]+)");
    Matcher m = p.matcher("some string and then a number 123.456789 and continue");
    while (m.find()) {
  System.out.println(m.group(1));
}
Sign up to request clarification or add additional context in comments.

6 Comments

Sorry, I didn't understand. What about this string: "122.34343The". And I want the number part: 122.34343
it will through a exception NumberFormatException: For input string: "122.34343The" and check this link too ideone.com/NWbT6F
Thank you soul. I found the answer and post it for others. +1 for your help.
@Natasha hmmm please update ur question its quiet confusing!!! anyways will upate my regex answer too
soul, if you saw the php floatval link that I've mentioned in my post you could exactly saw what I wanted. :)
|
0

Float#parseFloat parse String to float. But if string contain word character then it will throw NumberFormatException.

2 Comments

I don't need an exception. I need the Number part of the String. Thanks.
then you should extract the number then parse it.
0

I found the solution using regex:

Pattern p = Pattern.compile("([-+]?[0-9]*\\.?[0-9]+)");
Matcher m = p.matcher("some string and then a number 123.456789 and continue");

if ( m.find() ) {
  System.out.println(m.group(1)); // 123.456789
}

3 Comments

Could you provide me an example with your code that returns 123.456789 from the string: "some string 123.456789 and continue". Thanks.
So, that was not Exactly the same as floatval ;)
0

I have given a link to learn regarding converting float value from string which are as http://www.roseindia.net/java/beginners/ConvertStringToFloat.shtml I hope this one is very helpful for you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.