Convert String to Float and Back in Java – 在Java中把字符串转换成浮点数并返回

最后修改: 2021年 12月 30日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

Converting data from Float to String and vice-versa is an ordinary operation in Java. However, the many ways to do this may cause confusion and uncertainty about which to choose.

将数据从Float转换为String,反之亦然,这是Java中的一个普通操作。然而,许多方法可能会使人感到困惑,不知道该选择哪一种。

In this article, we will showcase and compare all the available options.

在这篇文章中,我们将展示和比较所有可用的选项。

2. Float to String

2.浮点字符串

First, let’s look at the most common ways to convert Float values to String.

首先,让我们看看将Float值转换为String的最常用方法。

2.1. String Concatenation

2.1.字符串串联

The most straightforward solution we can use is concatenating the floating-point value with an empty String.

我们可以使用的最直接的解决方案是将浮点值与一个空的String连接起来。

Let’s look at an example:

我们来看看一个例子。

float givenFloat = 1.25f;

String result = givenFloat + "";

assertEquals("1.25", result);

Similarly, we can add a Float object to the empty String and get the same result. When we use a Float object, its toString() method is called automatically:

类似地,我们可以将一个Float对象添加到空的String中,得到同样的结果。当我们使用Float对象时,其toString()方法会被自动调用。

Float givenFloat = 1.25f;

String result = givenFloat + "";

assertEquals("1.25", result);

If the Float object is null, the concatenation result will be a “null” String:

如果Float对象为空,连接的结果将是一个 “空”字符串

Float givenFloat = null;

String result = givenFloat + "";

assertEquals("null", result);

2.2. Float.toString()

2.2.Float.toString()

Another option we can use is the static toString() method of the Float class for String conversion. We can pass either a float primitive value or a Float object to the toString() method:

我们可以使用的另一个选项是Float类的静态toString()方法,用于String转换。我们可以将一个float原始值或一个Float对象传递给toString()方法:

Float givenFloat = 1.25f;

String result = Float.toString(givenFloat);

assertEquals("1.25", result);

If we pass null as an argument to the method, we’ll get a NullPointerException at runtime:

如果我们把null作为参数传给方法,我们会在运行时得到一个NullPointerException

Float givenFloat = null;

assertThrows(NullPointerException.class, () -> Float.toString(givenFloat));

2.3. String.valueOf()

2.3.String.valueOf()

Similarly, we can use String‘s static valueOf method:

同样地,我们可以使用String的静态valueOf方法。

Float givenFloat = 1.25f;

String result = String.valueOf(givenFloat);

assertEquals("1.25", result);

Unlike Float.toString()String.valueOf() will not throw an exception if we pass null as an argument, instead the “null” String is returned:

Float.toString()不同,String.valueOf()如果我们传递null作为参数,将不会抛出一个异常,而是返回 “null”String

Float givenFloat = null;

String result = String.valueOf(givenFloat);

assertEquals("null", result);

2.4. String.format()

2.4.String.format()

String‘s format() static method provides us with additional formatting options. We must be aware that without limiting the number of decimals, the result will contain trailing zeros even if there is no fractional part, as we can see in the following example:

Stringformat()静态方法为我们提供了额外的格式化选项。我们必须注意,如果不限制小数点的数量,即使没有小数部分,结果也会包含尾部的零,我们可以在下面的例子中看到。

Float givenFloat = 1.25f;

String result = String.format("%f", givenFloat);

assertEquals("1.250000", result);

When we format the floating-point number specifying the number of decimal places, the format() method will also round up the result:

当我们对浮点数进行格式化并指定小数点后的位数时,format()方法也会对结果进行四舍五入

Float givenFloat = 1.256f;

String result = String.format("%.2f", givenFloat);

assertEquals("1.26", result);

If we pass a null Float, then the converted result will be a “null” String:

如果我们传递一个空的Float,那么转换的结果将是一个 “空 “的String

Float givenFloat = null;

String result = String.format("%f", givenFloat);

assertEquals("null", result);

2.5. DecimalFormat

2.5. DecimalFormat

Lastly, the DecimalFormat class has a format() method that allows converting floating-point values to custom formatted Strings. The advantage is that we can define precisely how many decimals we want in our resulting String.

最后,DecimalFormat类有一个format()方法,可以将浮点值转换为自定义格式的字符串。这样做的好处是,我们可以精确地定义我们在生成的String中想要多少小数。

Let’s see how to use it in an example:

让我们看看如何在一个例子中使用它。

Float givenFloat = 1.25f;

String result = new DecimalFormat("#.0000").format(givenFloat);

assertEquals("1.2500", result);

If after we apply the formatting, there is no fractional part, DecimalFormat will return the whole number:

如果我们应用格式化后,没有小数部分,DecimalFormat将返回整数

Float givenFloat = 1.0025f;

String result = new DecimalFormat("#.##").format(givenFloat);

assertEquals("1", result);

If we pass null as an argument, then we will get an IllegalArgumentException:

如果我们传递null作为参数,那么我们将得到一个IllegalArgumentException

Float givenFloat = null;

assertThrows(IllegalArgumentException.class, () -> new DecimalFormat("#.000").format(givenFloat));

3. String to Float

3.将字符串转换为浮点运算

Next, let’s look at the most common ways to convert String values to Float.

接下来,让我们看看将String值转换为Float的最常用方法。

3.1. Float.parseFloat()

3.1. Float.parseFloat()

One of the most common ways is to use Float‘s static method: parseFloat(). It will return a primitive float value, represented by the String argument. Additionally, leading and trailing whitespaces are ignored:

最常见的方法之一是使用Float的静态方法。parseFloat()它将返回一个原始的float值,由String参数表示。此外,前导和尾部的空白将被忽略。

String givenString = "1.25";

float result = Float.parseFloat(givenString);

assertEquals(1.25f, result);

We get a NullPointerException if the String argument is null:

如果String参数为空,我们会得到一个NullPointerException

String givenString = null;

assertThrows(NullPointerException.class, () -> Float.parseFloat(givenString));

If the String argument does not contain a parsable float, we get a NumberFormatException:

如果String参数不包含可解析的float,我们会得到一个NumberFormatException:

String givenString = "1.23x";

assertThrows(NumberFormatException.class, () -> Float.parseFloat(givenString));

3.2. Float.valueOf()

3.2.Float.valueOf()

Similarly, we can use Float‘s static valueOf() method. The difference is that valueOf() returns a Float object. Specifically, it calls the parseFloat() method and boxes it into a Float object:

同样地,我们可以使用Float的静态valueOf()方法。区别在于,valueOf()返回一个Float对象。具体来说,它调用parseFloat()方法,并将其装箱为一个Float对象。

String givenString = "1.25";

Float result = Float.valueOf(givenString);

assertEquals(1.25f, result);

Identically, if we pass a non-parsable String, we will get a NumberFormatException:

同样,如果我们传递一个不可解析的String,我们将得到一个NumberFormatException

String givenString = "1.25x";

assertThrows(NumberFormatException.class, () -> Float.valueOf(givenString));

3.3. DecimalFormat

3.3. DecimalFormat

We can use DecimalFormat for converting String to Float as well. One of the main advantages is specifying custom decimal point separators.

我们也可以使用DecimalFormat来将String转换为Float主要优点之一是指定自定义小数点分隔符

String givenString = "1,250";
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
DecimalFormat decimalFormat = new DecimalFormat("#.000");
decimalFormat.setDecimalFormatSymbols(symbols);

Float result = decimalFormat.parse(givenString).floatValue();

assertEquals(1.25f, result);

3.4. Float‘s Constructor

3.4. Float的构造函数

Lastly, we can use Float‘s constructor directly for the conversion. Internally it will use Float‘s static parseFloat() method and create the Float object:

最后,我们可以直接使用Float的构造函数进行转换。在内部,它将使用Float的静态parseFloat()方法并创建Float对象:

String givenString = "1.25";

Float result = new Float(givenString);

assertEquals(1.25f, result);

As of Java 9, this constructor has been deprecated. Instead, we should consider using the other static factory methods such as parseFloat() or valueOf().

从Java 9开始,这个构造函数已经废弃了。 相反,我们应该考虑使用其他静态工厂方法,如parseFloat()valueOf()

4. Conclusion

4.总结

In this article, we have explored multiple ways for converting String instances to float or Float instances and back.

在这篇文章中,我们探讨了将String实例转换为floatFloat实例并返回的多种方法。

For simple conversions, String concatenation and Float.toString() would be the preferable options for transforming to String. If we need more complex formatting, then DecimalFormat is the best tool for the job. For converting strings to floating-point values, we can use Float.parseFloat() if we need a float primitive or Float.valueOf() if we prefer a Float object. Identically, for custom formatting, DecimalFormat is the best option.

对于简单的转换,String连接和Float.toString()将是转换为String的最好选择。如果我们需要更复杂的格式化,那么DecimalFormat就是最好的工具了。对于将字符串转换为浮点值,如果我们需要一个float基元,我们可以使用Float.parseFloat(),如果我们喜欢一个Float对象,可以使用Float.valueOf()。同样,对于自定义格式化,DecimalFormat是最佳选择。

As always, the code for these examples is available over on GitHub.

像往常一样,这些例子的代码可以在GitHub上找到over