js截取小数点后面2位

本文深入探讨了JavaScript中字符串操作方法substr以及数学函数toFixed、floor、ceil和round的使用方法,通过具体示例展示了如何进行字符串截取及数字的四舍五入、向下取整和向上取整操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.substr
var str = "Hello world!";
document.write(str.substr(3));
输出:lo world!

var str = "Hello world!";
document.write(str.substr(3,7));
输出:lo worl


2.toFixed(四舍五入)
var num = new Number(12.38);
document.write(num.toFixed(1));
输出:12.4
3.floor(向下取整) Math.floor(0.60); 结果:0 Math.floor(0.40); 0 Math.floor(5); 5 Math.floor(5.1); 5 Math.floor(-5.1); -6 Math.floor(-5.9); -6 3.ceil(向上取整) Math.ceil(0.60); 结果:1 Math.ceil(0.40); 1 Math.ceil(5); 5 Math.ceil(5.1); 6 Math.ceil(-5.1); -5 Math.ceil(-5.9); -5 4.round(四舍五入) Math.round(0.60); 结果:1 Math.round(0.40); 0 Math.round(5); 5 Math.round(5.1); 5 Math.round(-5.1); -5 Math.round(-5.9); -6 使用floor配合*100/100来实现向下取整截取小数点后两位 var num = 22.13758; console.log(Math.floor(num*100)/100); console.log(Math.ceil(num*100)/100); console.log(Math.round(num*100)/100); console.log(num.toFixed(2)); 输出:22.13 22.14 22.14 22.14

 

转载于:https://www.cnblogs.com/QW-lzm/p/9684084.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值