How to Formatting float and double numbers to string in Java

3 Answers

0 votes
import java.text.DecimalFormat;

public class MyClass {
    public static void main(String args[]) {
        DecimalFormat df = new DecimalFormat("#.##");
        
        String s = df.format(3.141592653595); 
        
        System.out.println(s); 
    }
}




/*
run:
      
3.14
      
*/

 



answered Nov 8, 2021 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        String s = String. format("%.2f", 3.141592653595);
        
        System.out.println(s); 
    }
}




/*
run:
      
3.14
      
*/

 



answered Nov 8, 2021 by avibootz
0 votes
import java.util.Formatter;

public class MyClass {
    public static void main(String args[]) {
        float pi = 3.141592653595f;
 
        StringBuilder sb = new StringBuilder();
        Formatter formatter = new Formatter(sb);  

        formatter.format("%.4f", pi);    
        System.out.println(formatter.toString());
        formatter.close();
    }
}




/*
run:
      
3.1416
      
*/

 



answered Nov 8, 2021 by avibootz

Related questions

...