强制保留两位小数的js方法
//写一个公共的强制保留两位小数的js方法 function toDecimal2 (x) { var f = parseFloat(x) if (isNaN(f)) { return false } var f = Math.round(x * 100) / 100 var s = f.toString() var rs = s.indexOf(‘.‘) if (rs < 0) { rs = s.length s += ‘.‘ } while (s.length <= rs + 2) { s += ‘0‘ } return s }
调用演示:
//调用演示 console.log( toDecimal2(2121) ); //2121.00 console.log( toDecimal2(2121.123) ); //2121.12 console.log( toDecimal2(2121.126) ); //2121.12
--------------------------------
在vue项目中可以配合vue.filter() 使用
<template> <div class="demo"> <span>{{‘1234.135‘ | toDecimal2}}</span> </div> </template> <script> export default { name: ‘‘, components: {}, data() { return {} }, filters: { toDecimal2 (x) { var f = parseFloat(x) if ( isNaN(f) ) { return false } var f = Math.round(x * 100) / 100 var s = f.toString() var rs = s.indexOf(‘.‘) if (rs < 0) { rs = s.length s += ‘.‘ } while (s.length <= rs + 2) { s += ‘0‘ } return s } }, } </script> <style scoped> </style>
END!!
来自:https://cloud.tencent.com/developer/article/1395547
原文:https://www.cnblogs.com/taohuaya/p/10859334.html