Wednesday 1 April 2020

Convert string to float

Approach 1: Using Float.parseFloat method
float f1 = Float.parseFloat(str);

Approach 2: Using 'Float.valueOf' method
float f2 = Float.valueOf(str).floatValue();

App.java
package com.sample.app;

public class App {

    public static void main(String args[]) {
        String str = "1.2345";

        float f1 = Float.parseFloat(str);
        float f2 = Float.valueOf(str).floatValue();

        System.out.println("f1: " + f1);
        System.out.println("f2: " + f2);
    }

}

Output
f1: 1.2345
f2: 1.2345

You may like

No comments:

Post a Comment