【问题标题】:java : convert float to String and String to floatjava:将浮点数转换为字符串,将字符串转换为浮点数
【发布时间】:2025-12-26 09:50:17
【问题描述】:

如何将浮点数转换为字符串或字符串转换为浮点数?

在我的情况下,我需要在 2 个值字符串(我从表中获得的值)和我计算的浮点值之间进行断言。

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

我试过从浮点数到字符串:

String sSelectivityRate = String.valueOf(valueCalculated );

但断言失败

【问题讨论】:

  • 知道 float 的值永远不会精确吗?
  • 您想将它们作为String 还是float 值进行比较?这不是一回事。 float 不如 double 精确,两者的计算值都可能存在舍入误差。
  • google 不要与 googol 混淆。 ;)
  • 我试过你的解决方案,也从护目镜,但是当我做出断言时,我得到了:java.lang.AssertionError: expected: but was:

标签: java string types number-formatting type-conversion


【解决方案1】:

走完整的手动路线:此方法通过移动数字的小数点并使用 floor(到 long)和模数来提取数字,将双精度数转换为字符串。此外,它使用基数除法来计算小数点所在的位置。一旦到达小数点后的位置,它还可以“删除”数字的较高部分,以避免超大双精度数丢失精度。请参阅最后的注释代码。在我的测试中,当它们实际显示这些不精确的小数点后位时,它的精确度永远不会低于 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 用于提高速度,但此方法可以轻松重写为使用数组,因此也适用于其他语言。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果您要查找,请说出两位小数。 Float f = (float)12.34; String s = new DecimalFormat ("#.00").format (f);

      【讨论】:

        【解决方案4】:
        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);
        

        【讨论】:

          【解决方案5】:

          好吧,这个方法不是很好,但很简单,不建议使用。也许我应该说这是最不有效的方法和更糟糕的编码实践,但使用起来很有趣,

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

          空引号,将空字符串添加到变量str,将'val'向上转换为字符串类型。

          【讨论】:

            【解决方案6】:

            使用 Java 的 Float 类。

            float f = Float.parseFloat("25");
            String s = Float.toString(25.0f);
            

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

            【讨论】:

            • 我需要导入一些东西才能让它工作吗?我得到了 undefied 类型 'Float'(虽然我在一个奇怪的 java 环境中,openhab 脚本)
            【解决方案7】:

            这是一个可能的答案,这也会给出精确的数据,只需要更改所需形式的小数点。

            公共类 TestStandAlone { /** *

            这个方法是main

            * @param 参数无效 */ 公共静态无效主要(字符串[]参数){ // TODO 自动生成的方法存根 尝试 { 浮点f1=152.32f; BigDecimal roundfinalPrice = new BigDecimal(f1.floatValue()).setScale(2,BigDecimal.ROUND_HALF_UP); System.out.println("f1 --> "+f1); 字符串 s1=roundfinalPrice.toPlainString(); System.out.println("s1"+s1); } 捕捉(异常 e){ // TODO 自动生成的 catch 块 e.printStackTrace(); } } }

            输出将是

            f1 --> 152.32 s1 152.32

            【讨论】:

              【解决方案8】:

              浮点到字符串 - 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)
              

              【讨论】:

                【解决方案9】:

                我相信以下代码会有所帮助:

                float f1 = 1.23f;
                String f1Str = Float.toString(f1);      
                float f2 = Float.parseFloat(f1Str);
                

                【讨论】:

                  【解决方案10】:

                  你可以试试这个代码示例:

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

                  找到here

                  【讨论】:

                  • 谢谢 - 帮助了我,需要捕捉位 ;)