java的四舍五入算法

粗力度的四舍五入为整数

 1 package math;  
 2   
 3 public class MathRoundTest {  
 4     /** 
 5      * Math类中提供了三个与取整有关的方法:ceil,floor,round, 
 6      * 这些方法的作用于它们的英文名称的含义相对应,例如:ceil的英文意义是天花板,该方法就表示向上取整, 
 7      * Math.ceil(11.3)的结果为12,Math.ceil(-11.6)的结果为-11;floor的英文是地板, 
 8      * 该方法就表示向下取整,Math.floor(11.6)的结果是11,Math.floor(-11.4)的结果-12; 
 9      * 最难掌握的是round方法,他表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整, 
10      * 所以,Math.round(11.5)的结果是12,Math.round(-11.5)的结果为-11.Math.round( )符合这样的规律: 
11      * 小数点后大于5全部加,等于5正数加,小于5全不加。 
12      */  
13     public static void main(String[] args) {     
14         System.out.println("小数点后第一位=5");     
15         System.out.println("正数:Math.round(11.5)=" + Math.round(11.5));     
16         System.out.println("负数:Math.round(-11.5)=" + Math.round(-11.5));     
17         System.out.println();     
18     
19         System.out.println("小数点后第一位<5");     
20         System.out.println("正数:Math.round(11.46)=" + Math.round(11.46));     
21         System.out.println("负数:Math.round(-11.46)=" + Math.round(-11.46));     
22         System.out.println();     
23     
24         System.out.println("小数点后第一位>5");     
25         System.out.println("正数:Math.round(11.68)=" + Math.round(11.68));     
26         System.out.println("负数:Math.round(-11.68)=" + Math.round(-11.68));  
27         /** 
28          * 运行结果: 
29             1、小数点后第一位=5 
30             2、正数:Math.round(11.5)=12 
31             3、负数:Math.round(-11.5)=-11 
32             4、 
33             5、小数点后第一位<5 
34             6、正数:Math.round(11.46)=11 
35             7、负数:Math.round(-11.46)=-11 
36             8、 
37             9、小数点后第一位>5 
38             10、正数:Math.round(11.68)=12 
39             11、负数:Math.round(-11.68)=-12 
40          */  
41         /** 
42          * 1、参数的小数点后第一位<5,运算结果为参数整数部分。 
43            2、参数的小数点后第一位>5,运算结果为参数整数部分绝对值+1,符号(即正负)不变。 
44            3、参数的小数点后第一位=5,正数运算结果为整数部分+1,负数运算结果为整数部分。 
45          */  
46     }     
47   
48 } 
View Code
原文地址:https://www.cnblogs.com/shangxiaofei/p/4788597.html