Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:

>> GET ACCESS NOW

1. Introduction

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.

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

2. Float to String

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

2.1. String Concatenation

The most straightforward solution we can use is concatenating the floating-point value with an empty 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 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 givenFloat = null;

String result = givenFloat + "";

assertEquals("null", result);

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 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:

Float givenFloat = null;

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

2.3. String.valueOf()

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

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 givenFloat = null;

String result = String.valueOf(givenFloat);

assertEquals("null", result);

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:

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:

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 givenFloat = null;

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

assertEquals("null", result);

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.

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:

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:

Float givenFloat = null;

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

3. String to Float

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

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:

String givenString = "1.25";

float result = Float.parseFloat(givenString);

assertEquals(1.25f, result);

We get a NullPointerException if the String argument is null:

String givenString = null;

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

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

String givenString = "1.23x";

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

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:

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 givenString = "1.25x";

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

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.

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

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:

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().

4. Conclusion

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

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.

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

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until end-of-day today:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!