您可能希望修剪源字符串,然后一次创建一个数字,同时计算可选小数点后出现的位数(以便您可以缩放结果数字)。
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;
}
}