话说做项目的时候,需要保留两位小数,本以为用toFixed()完美,然并卵…..
1 2 3 4 5
| 2.35.toFixed(1)
2.335.toFixed(2)
2.3335.toFixed(3)
|
解决办法-自己封装一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| function ToFixed(data,val){ var numbers = ''; for (var i = 0; i < val; i++) { numbers += '0'; } var s = 1 + numbers; var spot = "." + numbers; var value = Math.round(parseFloat(data) * s) / s; var d = value.toString().split("."); if (d.length == 1) { value = value.toString() + spot; return value; } if (d.length > 1) { if (d[1].length < 2) { value = value.toString() + "0"; } return value; } } ToFixed(2.335,2)
|