Java中Math.round()方法

最近我也在看一些书籍,发现了好多不知道的方法和用法,所以才给大家分享出来,顺便做一个小总结!

先介绍这个方法Math.round()

Java中的Math.round()方法是将浮点型进行“四舍五入”转换为int类型的一个方法(不含小数点.0)!
但是它的“四舍五入”方式有点特别,区别于保留两位小数的四舍五入!
而Math.round()方法是在java.lang包下,所以我们也无需导包!

这是这一个类似“四舍五入”的方法,而且还引申出了这两个方法Math.floor()和Math.ceil()

Math.floor()意为向下取整,也就是说不管你小数点后的数字是几,它只保留原整数和一个小数点位数.0(逢数就舍)

Math.ceil()意为向上取整,相同的是不管你小数点后的数字是几,它都必须给原整数向上进一,然后再保留一个小数点位数.0(逢数进一,遇见小数不管是多少都进一)
特殊案例:10.0等临界值除外,它不会再向上取整,只会保留一个小数位但值不会发生改变

如果你不明白,可以去看一下举的例子,还可以去复制一下例子自己打印一下或许就知道了其中的端倪!(我将打印结果附在了代码后方的注释)

真正的保留两位小数请参考:Java怎么保留两位小数

举个栗子

/** 
* @author Ziph
* @date 2020年3月8日
* @Email [email protected]
*/
public class TestMathRound {
	public static void main(String[] args) {
		//Math.round()——特殊四舍五入取整
		System.out.println(Math.round(10.5));	//11
		System.out.println(Math.round(10.4));	//10
		System.out.println(Math.round(10.9));	//11
		System.out.println(Math.round(10.0));	//10
		
		//(Math.ceil()——向上取整
		System.out.println(Math.ceil(10)); 		//10.0
		System.out.println(Math.ceil(10.0));	//10.0
		System.out.println(Math.ceil(10.01));	//11.0
		
		//Math.floor()——向下取整
		System.out.println(Math.floor(10.9));	//10.0
		System.out.println(Math.floor(10));		//10.0
	}
}

发布了103 篇原创文章 · 获赞 162 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_44170221/article/details/104731124