js
number.toFixed(digits)الناتج string مش number — حوّله بـNumber() لو هتحسب بيه. بسبب التمثيل الثنائي للأرقام في JavaScript، نتائج زي (1.005).toFixed(2) ممكن تفاجئك: بتدّي '1.00' مش '1.01'.
حالات حدّية
- (1.005).toFixed(2) === '1.00': الرقم 1.005 مش متمثّل بدقة، فبيتقرب لأقل. لو الدقة المالية مهمة استخدم حسابات بالقرش الصحيح مش بالعشري.
- digits من 0 لـ100 بس؛ برّه المدى بترمي RangeError.
البرهان
js
console.log((3.14159).toFixed(2));
console.log(typeof (3.14159).toFixed(2));
console.log((2.5).toFixed(0), (3.5).toFixed(0));
console.log((1.005).toFixed(2));
console.log(Number((3.14159).toFixed(1)) + 1);
try {
(1).toFixed(101);
} catch (e) {
console.log(e.constructor.name);
}النتيجة
3.14 string 3 4 1.00 4.1 RangeError