Java – Parse float from string containing letters

This post shows you how to parse a string containing letters to a float using Java. To do this, we need to use NumberFormat class to parse a string to a float.

For example, we want to parse the following strings to the float:

Input (String) Output (Float)
123abcd 123.0
20.4fcdw31 20.4
15.0ab23 15.0

Let’s consider the below code example:
package com.bytenota;

import java.text.NumberFormat;
import java.text.ParseException;

public class StringExample {
    public static void main(String[] args) throws ParseException {
        String str1 = "123abcd";
        float result1 = NumberFormat.getInstance().parse(str1).floatValue();
        System.out.println(result1); // 123.0
        String str2 = "20.4fcdw31";
        float result2 = NumberFormat.getInstance().parse(str2).floatValue();
        System.out.println(result2); // 20.4
        String str3 = "15.0ab23";
        float result3 = NumberFormat.getInstance().parse(str3).floatValue();
        System.out.println(result3); // 15.0

0 0 vote
Article Rating
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x