taktoa
taktoa

Reputation: 554

Generalized number to string conversion in Java

I'm working on a program in Java and I have run into a small problem. I'm accepting user input that includes a number, but I have no way of knowing how that number is represented (i.e.: it could be "42", "42.0", "42.00001", etc.). If I use, say, Float.parseFloat, it won't accept integer strings ("42"), while if I use Integer.parseInteger, it won't accept float strings ("42.0"). Is there any kind of generalized string-to-number conversion function in Java?

Thanks in advance.

Upvotes: 1

Views: 208

Answers (2)

chucksmash
chucksmash

Reputation: 5997

public class Q9146065 {
    public static void main(String[] args) {
        String test = "32";
        float a = Float.parseFloat(test);
        float b = 10;
        System.out.println(a + b);
    }
}

Sure enough prints out 42.0 for me so it is parsing 32 fine...

Upvotes: 0

DraganS
DraganS

Reputation: 2699

You could use Float.parseFloat

groovy> Float.parseFloat("4")
4.0

Upvotes: 2

Related Questions