![](/img/trans.png)
[英]Extending Number.prototype in javascript and the Math object?
[英]Add a rounding method to Number.prototype in JavaScript
如何簡化JavaScript中的舍入? 我希望我能以一種面向對象的方式更優雅地做到這一點。 toFixed方法效果很好,但是沒有向后舍入,它還會返回字符串而不是數字。
pi.toFixed(2).valueOf();
// 3.14
實際上,舍入有點糾結,因為我必須使用:
pi = Math.round(pi * 100) / 100;
// 3.14
相反,將方法粘貼到變量的末尾會更好,例如:
pi.round(2);
// 3.1r
擴展Number.prototype。 Javascript中的數字是與內置對象“ Number”關聯的數據類型。 添加以下polyfill塊:
if (!Number.prototype.round) {
Number.prototype.round = function (decimals) {
if (typeof decimals === 'undefined') {
decimals = 0;
}
return Math.round(
this * Math.pow(10, decimals)
) / Math.pow(10, decimals);
};
}
在此之后的任何地方,都可以通過將.round()粘貼到數字的末尾來四舍五入。 它具有一個可選參數,該參數確定小數位數。 例如:
pi.round(2);
您還可以對負數使用向后舍入,例如:
x = 54321;
x.round(-4);
// 50000
小提琴: http : //jsfiddle.net/g2n2fbmq/
有關:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.