Java中如何将浮点数转换为字符串,以及如何将字符串转换为浮点数

230

如何进行浮点数与字符串之间的转换?

在我的情况下,我需要对比从表格中获取的字符串值和我计算得出的浮点数值。

String valueFromTable = "25";
Float valueCalculated =25.0;

我尝试将浮点数转换为字符串:

String sSelectivityRate = String.valueOf(valueCalculated);

但是断言失败了


11
你知道 float 类型的值永远不会精确吗? - xtofl
1
你想将它们作为“String”还是“float”值进行比较?这不是同一件事。“float”比“double”精度低,两者都可能存在由计算值引起的舍入误差。 - Peter Lawrey
3
谷歌不要与 googol 混淆。 ;) - Peter Lawrey
我尝试了您的解决方案和谷歌上的解决方案,但是当我进行断言时,我得到了以下错误:java.lang.AssertionError: expected:<25> but was:<25.0>。 - lola
10个回答

400
使用Java的Float类。
float f = Float.parseFloat("25");
String s = Float.toString(25.0f);

为了进行比较,最好将字符串转换为浮点数并将其作为两个浮点数进行比较。这是因为对于一个浮点数,有多个字符串表示形式,当作为字符串进行比较时它们是不同的(例如,“25”!=“25.0”!=“25.00”等)。


我需要导入一些东西才能让它工作吗?我得到了未定义类型“Float”的错误(尽管我处在一个奇怪的Java环境中,即openhab脚本)。 - Jonathan
一般来说,比较浮点数的相等性是一个不好的主意。 - undefined

37

将浮点数转换为字符串 - String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

字符串转浮点数 - Float.parseFloat()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

5
你可以尝试这段代码样例:
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());
    }
  }
}

这里找到了答案。


谢谢 - 帮了我大忙,我需要捕获代码块 ;) - Hein du Plessis

3
我相信以下代码会有所帮助:
float f1 = 1.23f;
String f1Str = Float.toString(f1);      
float f2 = Float.parseFloat(f1Str);

2
如果你想保留两位小数,可以使用以下代码: Float f = (float)12.34; String s = new DecimalFormat ("#.00").format (f); 其中,f代表需要保留两位小数的数字,s代表格式化后的结果。

2

这是一个可能的答案,它也会提供精确的数据,只需要在所需的形式中更改小数点。

public class TestStandAlone {
/** *

此方法是主入口点

* @param args void */ public static void main(String[] args) { // TODO Auto-generated method stub try { Float f1=152.32f; BigDecimal roundfinalPrice = new BigDecimal(f1.floatValue()).setScale(2,BigDecimal.ROUND_HALF_UP);
System.out.println("f1 --> "+f1); String s1=roundfinalPrice.toPlainString(); System.out.println("s1 "+s1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
}

输出结果将是

f1 --> 152.32
s1 152.32

1

这个方法并不好,但很容易实现,不建议使用。也许我应该说这是最不有效的方法和最糟糕的编程实践,但是它很有趣。

float val=10.0;
String str=val+"";

在变量str中添加一个空字符串,将'val'向上转型为字符串类型。

1

三种方法将浮点数转换为字符串。

  1. "" + f
  2. Float.toString(f)
  3. String.valueOf(f)

两种方法将字符串转换为浮点数

  1. Float.valueOf(str)
  2. Float.parseFloat(str);

例子:

public class Test {

    public static void main(String[] args) {
        System.out.println("convert FloatToString " + convertFloatToString(34.0f));

        System.out.println("convert FloatToStr Using Float Method " + convertFloatToStrUsingFloatMethod(23.0f));

        System.out.println("convert FloatToStr Using String Method " + convertFloatToStrUsingFloatMethod(233.0f));

        float f = Float.valueOf("23.00");
    }

    public static String convertFloatToString(float f) {
        return "" + f;
    }

    public static String convertFloatToStrUsingFloatMethod(float f) {
        return Float.toString(f);
    }

    public static String convertFloatToStrUsingStringMethod(float f) {
        return String.valueOf(f);
    }

}

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

0

使用完全手动的方法:这种方法通过移动数字的小数点并使用floor(to long)和模运算来提取数字来将doubles转换为字符串。此外,它使用以基数除法计数来确定小数点所属的位置。一旦到达小数点后的位数,它也可以“删除”数字的更高部分,以避免在超大doubles上失去精度。请参见末尾的已注释代码。在我的测试中,当Java浮点表示实际显示这些不精确的较低小数位时,它从未比Java浮点表示本身更不精确。

/**
 * Convert the given double to a full string representation, i.e. no scientific notation
 * and always twelve digits after the decimal point.
 * @param d The double to be converted
 * @return A full string representation
 */
public static String fullDoubleToString(final double d) {
    // treat 0 separately, it will cause problems on the below algorithm
    if (d == 0) {
        return "0.000000000000";
    }
    // find the number of digits above the decimal point
    double testD = Math.abs(d);
    int digitsBeforePoint = 0;
    while (testD >= 1) {
        // doesn't matter that this loses precision on the lower end
        testD /= 10d;
        ++digitsBeforePoint;
    }

    // create the decimal digits
    StringBuilder repr = new StringBuilder();
    // 10^ exponent to determine divisor and current decimal place
    int digitIndex = digitsBeforePoint;
    double dabs = Math.abs(d);
    while (digitIndex > 0) {
        // Recieves digit at current power of ten (= place in decimal number)
        long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10;
        repr.append(digit);
        --digitIndex;
    }

    // insert decimal point
    if (digitIndex == 0) {
        repr.append(".");
    }

    // remove any parts above the decimal point, they create accuracy problems
    long digit = 0;
    dabs -= (long)Math.floor(dabs);
    // Because of inaccuracy, move to entirely new system of computing digits after decimal place.
    while (digitIndex > -12) {
        // Shift decimal point one step to the right
        dabs *= 10d;
        final var oldDigit = digit;
        digit = (long)Math.floor(dabs) % 10;
        repr.append(digit);

        // This may avoid float inaccuracy at the very last decimal places.
        // However, in practice, inaccuracy is still as high as even Java itself reports.
        // dabs -= oldDigit * 10l;
        --digitIndex;
    }

    return repr.insert(0, d < 0 ? "-" : "").toString(); 
}

请注意,尽管StringBuilder用于加速,但此方法很容易被重写为使用数组,因此也适用于其他编程语言。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接