Search code examples
javastringcastingcharacterfloating-point-conversion

How to convert a String to a Float character by character using Java?


I was asked this on an interview a while back and couldn't figure it out. I wasn't allowed to cast the entire thing at once so my next idea was to just run through the string converting until the point but the guy interviewing me told me he wanted to do something like this:

1 = 1 
12 = 1 * 10 + 2 
123 = 12 * 10 + 3 
1234 = 123 * 10 + 4

The input is convert "1234.567" to a float ie. 1234.567

I honestly have no idea how he meant to do it and I haven't been able to produce good enough code to show you guys all I had was the for cycling to parse each character:

for(int i = 0; i < str.length(); i++){
        if(!str.charAt(i).equals(".")){
            fp = Float.parseFloat("" + str.charAt(i));

Solution

  • This isn't especially elegant, but does work.

        String s = "1234.567";
        Float fp = 0f;
        Float fpd = 0f;
        int i =0;
        while(s.charAt(i) != '.') {
                fp = (fp * 10) + Float.parseFloat(s.substring(i, (i+1)));
                i++;
            }
        int d = s.indexOf('.');
        for(i = s.length()- 1; i > d; i--) {
            fpd = (fpd * 0.1f) + (Float.parseFloat(s.substring(i, (i+1))) * 0.1f);  
        }
        fp += fpd;
        System.out.println(fp);