How to format float to N decimal places in Java

3 Answers

0 votes
package javaapplication1;

import java.io.IOException;

public class JavaApplication1 {

    public static void main(String[] args) throws IOException {

        try {

            float f = 3.14159265359f;
            
            System.out.format("%.2f\n", f);
            

        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

/*
           
run:
     
3.14
  
 */

 



answered Nov 19, 2016 by avibootz
0 votes
package javaapplication1;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class JavaApplication1 {

    public static void main(String[] args) throws IOException {

        try {

            float f = 3.14159265359f;

            NumberFormat formatter = new DecimalFormat("0.00");

            System.out.println(formatter.format(f));

        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

/*
           
run:
     
3.14
  
 */

 



answered Nov 19, 2016 by avibootz
0 votes
package javaapplication1;

import java.io.IOException;

public class JavaApplication1 {

    public static void main(String[] args) throws IOException {

        try {

            float f = 3.14159265359f;

            String s = String.format("%.2f", f);

            System.out.println(s);

        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

/*
           
run:
     
3.14
  
 */

 



answered Nov 19, 2016 by avibootz

Related questions

1 answer 228 views
2 answers 199 views
1 answer 159 views
1 answer 133 views
1 answer 165 views
...