Wednesday 1 April 2020

Convert Float to a string

Approach 1: Use toString() method of Float class.
String str1 = floatVar.toString();
String str2 = Float.toString(floatVar);

Approach 2: Using FloatingDecimal.toJavaFormatString.
String str3 = FloatingDecimal.toJavaFormatString(floatVar);

Approach 3: Using String.valueOf method.
String str4 = String.valueOf(floatVar);

Approach 4: Using DecimalFormat.
String str5 = new DecimalFormat("#.00").format(floatVar);

Find the below working application.

App.java
package com.sample.app;

import java.text.DecimalFormat;

import sun.misc.FloatingDecimal;

public class App {

    public static void main(String args[]) {
        Float floatVar = 1.2345f;

        String str1 = floatVar.toString();
        String str2 = Float.toString(floatVar);
        String str3 = FloatingDecimal.toJavaFormatString(floatVar);
        String str4 = String.valueOf(floatVar);
        String str5 = new DecimalFormat("#.00").format(floatVar);
        
        System.out.println("str1 : " + str1);
        System.out.println("str2 : " + str2);
        System.out.println("str3 : " + str3);
        System.out.println("str4 : " + str4);
        System.out.println("str5 : " + str5);
    }

}

Output

str1 : 1.2345
str2 : 1.2345
str3 : 1.2345
str4 : 1.2345
str5 : 1.23

You may like

No comments:

Post a Comment