js截取小數點后面2位


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM