如何从浮点数转换为字符串或字符串转换为浮点数?
在我的情况下,我需要使断言之间的2值字符串(值,我已经从表)和浮动值,我已经计算。
String valueFromTable = "25";
Float valueCalculated =25.0;
我尝试了从float到string:
String sSelectivityRate = String.valueOf(valueCalculated);
但是这个断言不成立
如何从浮点数转换为字符串或字符串转换为浮点数?
在我的情况下,我需要使断言之间的2值字符串(值,我已经从表)和浮动值,我已经计算。
String valueFromTable = "25";
Float valueCalculated =25.0;
我尝试了从float到string:
String sSelectivityRate = String.valueOf(valueCalculated);
但是这个断言不成立
当前回答
您可以尝试以下示例代码:
public class StringToFloat
{
public static void main (String[] args)
{
// String s = "fred"; // do this if you want an exception
String s = "100.00";
try
{
float f = Float.valueOf(s.trim()).floatValue();
System.out.println("float f = " + f);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
在这里找到
其他回答
使用Java的Float类。
float f = Float.parseFloat("25");
String s = Float.toString(25.0f);
要比较,最好是将字符串转换为浮点数,然后作为两个浮点数进行比较。这是因为对于一个浮点数有多个字符串表示形式,当将其作为字符串进行比较时是不同的(例如。"25" != "25.0" != "25.00"等等)
String str = "1234.56";
float num = 0.0f;
int digits = str.length()- str.indexOf('.') - 1;
float factor = 1f;
for(int i=0;i<digits;i++) factor /= 10;
for(int i=str.length()-1;i>=0;i--){
if(str.charAt(i) == '.'){
factor = 1;
System.out.println("Reset, value="+num);
continue;
}
num += (str.charAt(i) - '0') * factor;
factor *= 10;
}
System.out.println(num);
您可以尝试以下示例代码:
public class StringToFloat
{
public static void main (String[] args)
{
// String s = "fred"; // do this if you want an exception
String s = "100.00";
try
{
float f = Float.valueOf(s.trim()).floatValue();
System.out.println("float f = " + f);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
在这里找到
这个方法不是很好,但是很简单,不建议使用。也许我应该说这是最无效的方法,也是最糟糕的编码实践,但是,使用起来很有趣,
float val=10.0;
String str=val+"";
空引号,将一个空字符串添加到变量str,将'val'上转换为字符串类型。
- string . valueof ()
float amount=100.00f;
String strAmount=String.valueOf(amount);
// or Float.toString(float)
String to Float - Float. parsefloat ()
String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or Float.valueOf(string)