您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JavaScript中保留小数与取整数

2024/3/6 8:33:53发布25次查看
保留小数与取整数应该算是很小的知识点,但小知识点不代表没有用。
     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是向下取整数,只入不舍。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product