简体   繁体   English

如何使用Java逐字符将String转换为Float字符?

[英]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 输入convert "1234.567" to a float ie. 1234.567 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));

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. 当然,您受float可以表示为十进制数字的限制-最终,数量不多。 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). 尤其是在这种情况下,您一直都在进行乘法/加法运算,而不必讨论最终除法(如果除数不为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. 关于上述内容的有趣注释:实际上,这似乎可能在不同平台上产生不同的结果...现代平台上的现代JVM可能使用内部的,高精度的浮点中间表示形式。 If you want the same result everywhere, you have to add the modifier strictfp to the method declaration: 如果在任何地方都希望得到相同的结果,则必须在方法声明中添加修饰符strictfp

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. 您是否要将“ 123456”之类的整数转换为“ 12345 * 10 + 6”,如果要执行此操作,只需使用“ substring”方法即可。

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

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. 这将给我们1234。

We now then need to format it such that we get 1234 = 123 * 10 + 4. 然后,我们现在需要对其进行格式化,以便获得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. 数学上,当您将1234除以10时,商将为123,余数为4。这将为您提供该家伙想要的答案。

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

package com.nanofaroque.float2String; 包com.nanofaroque.float2String;

public class Float2String { 公共类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);
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM