Question

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));
Was it helpful?

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);

OTHER TIPS

Something like this (note: no error checking):

public float parseFloatFromString(final String input)
{
    boolean seenDot = false;
    float divisor = 1.0f;
    char c;
    float ret = 0.0f;

    for (int i = 0; i < input.length(); i++) {
        c = input.charAt(i);
        if (c == '.') {
            seenDot = true;
            continue;
        }
        ret *= 10.0f;
        ret += (float) (c - '0');
        if (seenDot)
            divisor *= 10.0f;
    }

    ret /= divisor;
    return ret;
}

Of course, you are limited by what a float can represent as decimal numbers -- ultimately, not much. Especially in this case where you multiply/add all the time, and let's not talk about the final division (if the divisor is not 1).

Interesting note about the above: in fact, it appears that this may yield different results on different platforms... Modern JVMs on modern platforms may use an internal, higher precision intermediate representation for floating points. If you want the same result everywhere, you have to add the modifier strictfp to the method declaration:

public strictfp float parseFloatFromString(final String input)

More details here.

I can't understand what's your meaning? Did you meaning that convert the integer like '123456' to '12345 * 10 + 6', if you want to do this, just use the 'substring' method to do this.

You would want to trim the source string and then create the number a digit at a time, while counting how many digits occur after an optional decimal point (so you can scale the resulting number).

public class MakeFloat {

private static MakeFloat me;

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    me = new MakeFloat();
    String source = " 1234.567";
    float result = me.start(source);
    System.out.println(" " + source + "=" + result);
}

private float start(String string) {
    final String digits = "0123456789";
    final float[] values = {0,1,2,3,4,5,6,7,8,9};
    float ten = 10;

    float result = 0;
    float scale = 1;
    boolean isAfterDecimal = false;

    String stepThrough = string.trim();

    for (int i = 0; i < stepThrough.length(); i++) {
        // see if we have a digit or a decimal point
        String digit = stepThrough.substring(i, i + 1);
        int loc = digits.indexOf(digit);
        if (loc > -1) {
            result = ten * result + values[loc];
            if (isAfterDecimal) {
                scale = scale * ten;
            }
        } else if (".".equals(digit)) {
                  if (isAfterDecimal) {
                    // handle error
                  } else {
                    isAfterDecimal = true;
                  }
        } else {
                // handle bad character
        }
    }
    return result / scale;
}
}

To convert a string to a float, I personally use this:

Float.parseFloat("1234.567");

For what the guy wanted, this would be my way of doing it:

String num = "1234.567";

int dotLocation = num.indexOf(".");
int wholeNum = Integer.parseInt(num.substring(0, dotLocation)); 

String answer = (wholeNum / 10) + " * 10 + " + (wholeNum % 10); 

Locate the position of the "." in the string, then extract the whole number by taking a substring of the original string. This would give us 1234.

We now then need to format it such that we get 1234 = 123 * 10 + 4.

Mathematically, when you divide 1234 by 10, the quotient would be 123 and the remainder would be 4. This would give you the answer the guy wanted.

package com.nanofaroque.float2String;

public class Float2String {

public static void main(String[] args) {
    String input="1234.56";
    String str=".";
    float result=0;
    int j=3;//this is used for multiply by 10^j

    for(int i=0;i<input.length();i++){
        if (input.charAt(i)!=str.charAt(0)){
            char m=input.charAt(i);//Convert String to Character
            float x=(float) input.charAt(i);//Getting the ASCI value
            x=x-48;//Now x converted to the real float value
            float y=(float) (x* (Math.pow(10, j)));//Multiplication Operation for conversion
            result=result+y;
            j=j-1;
                        }
        else{
            System.out.println("Welcome to my World");// to make the loop work..You can change it if you want
        }
    }
    System.out.println("Result after the conversion:"+result);
}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top