JavaScript如何实现数据的四舍五入

清浅
清浅 原创
2019-01-16 14:37:55 4451浏览

实现数据的四舍五入有以下几种方法:round方法、tofixed方法、parseInt方法、ceil方法以及floor方法

在JavaScript 对数值进行四舍五入的操作有以下几种

round()方法:可把一个数字舍入为最接近的整数,即四舍五入

toFixed()方法:可把 Number 四舍五入为指定小数位数的数字。

parseInt()方法:可将小数转化为整数(位操作符)

ceil()方法:可对一个数进行上舍入

floor()方法:可对一个数进行下舍入

接下来在文章中将和大家详细介绍这几种方法的具体用法

round()方法

	document.write(Math.round(4.55) + "<br>");
	document.write(Math.round(-6.45));

效果图:


toFixed()方法

var num=3.141592;
document.write(num.toFixed(2));

效果图:

parseInt()方法

document.write(parseInt("12.333"));
	

效果图:

Image 17.jpg

ceil()方法与floor()方法

document.write("ceil方法:")
document.write(Math.ceil("12.333") + "<br>");
document.write("floor方法:")
document.write(Math.floor("12.333"));

效果图:

Image 18.jpg

以上就是JavaScript如何实现数据的四舍五入的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。