How to round a float number to N specified decimal places in Java

2 Answers

0 votes
import java.math.BigDecimal;

public class MyClass {
    public static void main(String args[]) {
        float num = 378.538721f;        
		int decimal_places = 3;
		
		BigDecimal bd = new BigDecimal(Float.toString(num));
        bd = bd.setScale(decimal_places, BigDecimal.ROUND_HALF_UP); 

        System.out.println(bd);
    }
}




/*
run:

378.539

*/

 



answered Aug 9, 2021 by avibootz
0 votes
import java.text.DecimalFormat;
import java.math.RoundingMode;

public class MyClass {
    public static void main(String args[]) {
        float num = 378.538721f;        

	    DecimalFormat df = new DecimalFormat("#.###");
        df.setRoundingMode(RoundingMode.CEILING);
        
        System.out.println(df.format(num));
    }
}




/*
run:

378.539

*/

 



answered Aug 9, 2021 by avibootz
edited Aug 9, 2021 by avibootz

Related questions

2 answers 280 views
3 answers 298 views
1 answer 266 views
1 answer 160 views
...