Java 四舍五入运算

-- Start

Java 的 Math 和 StrictMath 类提供了一些关于数学运算的静态方法. Math 类中的方法运行速度更快而 StrictMath 类中的方法更为精确.

Math 和 StrictMath 类提供了以下四个方法来进行四舍五入运算.

ceil // 天花板
round // 四舍五入, 返回整数
rint // 四舍五入, 返回浮点数
floor // 地板
来看下面代码的结果, 你就知道它们的意思了.
	public static void main(String[] args) {
		System.out.println("ceil testing");
		System.out.println("1.4 --ceil--> " + Math.ceil(1.4));
		System.out.println("1.5 --ceil--> " + Math.ceil(1.5));
		System.out.println("-1.4 --ceil--> " + Math.ceil(-1.4));
		System.out.println("-1.5 --ceil--> " + Math.ceil(-1.5));
		System.out.println();

		System.out.println("round testing");
		System.out.println("1.4 --round--> " + Math.round(1.4));
		System.out.println("1.5 --round--> " + Math.round(1.5));
		System.out.println("-1.4 --round--> " + Math.round(-1.4));
		System.out.println("-1.5 --round--> " + Math.round(-1.5));
		System.out.println();

		System.out.println("rint testing");
		System.out.println("1.4 --rint--> " + Math.rint(1.4));
		System.out.println("1.5 --rint--> " + Math.rint(1.5));
		System.out.println("-1.4 --rint--> " + Math.rint(-1.4));
		System.out.println("-1.5 --rint--> " + Math.rint(-1.5));
		System.out.println();

		System.out.println("floor testing");
		System.out.println("1.4 --floor--> " + Math.floor(1.4));
		System.out.println("1.5 --floor--> " + Math.floor(1.5));
		System.out.println("-1.4 --floor--> " + Math.floor(-1.4));
		System.out.println("-1.5 --floor--> " + Math.floor(-1.5));
	}

结果

ceil testing
1.4 --ceil--> 2.0
1.5 --ceil--> 2.0
-1.4 --ceil--> -1.0
-1.5 --ceil--> -1.0

round testing
1.4 --round--> 1
1.5 --round--> 2
-1.4 --round--> -1
-1.5 --round--> -1

rint testing
1.4 --rint--> 1.0
1.5 --rint--> 2.0
-1.4 --rint--> -1.0
-1.5 --rint--> -2.0

floor testing
1.4 --floor--> 1.0
1.5 --floor--> 1.0
-1.4 --floor--> -2.0
-1.5 --floor--> -2.0

---更多参见:Java 精萃
-- 声 明:转载请注明出处
-- Last Updated on 2012-04-25
-- Written by ShangBo on 2012-04-25
-- End


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值