Home >Web Front-end >JS Tutorial >Keeping decimals and taking integers in JavaScript

Keeping decimals and taking integers in JavaScript

巴扎黑
巴扎黑Original
2016-11-25 14:18:151870browse

保留小数与取整数应该算是很小的知识点,但小知识点不代表没有用。

     1.toFixed()方法(保留小数)

      用法是比较简单的,如下:

var number=521;  
var number2=521.1314;  
number.toFixed(2);  
console.log(number);//结果:521  
console.log(number.toFixed(2))//结果:521.00  
console.log(number2.toFixed(2))//结果:521.13

     其中number是数字类型变量,toFixed()括号中是要保留的位数,0~20位一般不会出现问题,number小数位数太长会出现RangeError异常,number如果不是数字类型就会出现TypeError异常,要注意的是toFixed()书写时F一定要大写。

     2.Math.fioor()方法(向下取整数)

var number=521.1314;  
Math.floor(number);  
console.log(number);结果521.1314  
console.log(Math.floor(number));结果521

    可以看到Math.floor是向下取整,括号中是数字变量,只舍不如,Math的M要大写。

     3.Math.ceil()方法(向上取整数)  

var number=00543.44944  
Math.ceil(number);  
console.log(number);结果00543.44944  
console.log(Math.ceil(number));结果00544

    很明显,Math.ceil()用法和Math.floor()方法很相似,不同的是Math.ceil是向下取整数,只入不舍。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn