Conversion from String to Float in Java

Java conversion from String to Float: Here, we are going to learn how to convert a given string value to a float in Java?
Submitted by IncludeHelp, on July 16, 2019

Given a string and we have to convert it into a float.

Java conversion from String to Float

To convert a String to Float, we can use the following methods of Float class (see the syntax given below...)

Syntax:

    Float Float.valueOf(String).floatValue();
    OR
    Float Float.parseFloat(String);

Java code to convert a String to Float

//Java code to convert String to Float
public class Main {
    public static void main(String args[]) {
        String str = "1234.587878f";

        //variable to store result
        float result = 0;

        //converting string to Float
        //method 1
        result = Float.valueOf(str).floatValue();
        System.out.println("result (value of str as float) = " + result);

        //method 2
        result = Float.parseFloat(str);
        System.out.println("result (value of str as float) = " + result);
    }
}

Output

result (value of str as float) = 1234.5879
result (value of str as float) = 1234.5879

Java Conversion Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.