Math.round بتقرّب لأنصاف ناحية +∞، فالسالب بيمشي عكس اللي متوقعه: -1.5 بتبقى -1، و-0.4 بترجّع -0.
المثال
Math.round بتقرّب لأنصاف لأعلى ناحية +∞، مش بعيد عن الصفر. فـ-1.5 بتبقى -1، و-0.5 بتبقى -0. ولو عايز تقريب بعيد عن الصفر، لازم تكتبه بنفسك.
-1.5 طلعت -1 و1.5 طلعت 2. و-0.5 و-0.4 رجّعوا -0، وObject.is أكّدت إنها -0 مش 0. floor رجّعت -2، وtrunc وceil رجّعوا -1. والصيغة المتماثلة sign × round(abs) رجّعت -2. وJSON.stringify كتبت -0 كـ0.
اختيار الدالة
trunc بتشيل الكسر، وfloor بتنزل لأقل عدد صحيح، وceil بتطلع لأعلى. للسالب floor بعيد عن الصفر وtrunc قريب منه. ولو محتاج تقريب متماثل (نص لفوق ونص لتحت)، اكتبه بـMath.sign وMath.abs.
-0 موجودة في JS ومختلفة عن 0 في Object.is، وبتظهر كـ0 في JSON.stringify.
البرهان
console.log('round(-1.5):', Math.round(-1.5), '| round(-0.5):', Math.round(-0.5), '| round(1.5):', Math.round(1.5));
console.log('floor(-1.5):', Math.floor(-1.5), '| trunc(-1.5):', Math.trunc(-1.5), '| ceil(-1.5):', Math.ceil(-1.5));
console.log('floor(1.5):', Math.floor(1.5), '| trunc(1.5):', Math.trunc(1.5));
const v = -0.4;
console.log('round(-0.4):', Math.round(v), '| Object.is(-0):', Object.is(Math.round(v), -0));
console.log('التقريب المتماثل:', Math.sign(-1.5) * Math.round(Math.abs(-1.5)));
console.log('JSON للناقص صفر:', JSON.stringify(Math.round(v)));round(-1.5): -1 | round(-0.5): -0 | round(1.5): 2 floor(-1.5): -2 | trunc(-1.5): -1 | ceil(-1.5): -1 floor(1.5): 1 | trunc(1.5): 1 round(-0.4): -0 | Object.is(-0): true التقريب المتماثل: -2 JSON للناقص صفر: 0
console.log('round(-1.5):', Math.round(-1.5), '| round(-0.5):', Math.round(-0.5), '| round(1.5):', Math.round(1.5));
console.log('floor(-1.5):', Math.floor(-1.5), '| trunc(-1.5):', Math.trunc(-1.5), '| ceil(-1.5):', Math.ceil(-1.5));
console.log('floor(1.5):', Math.floor(1.5), '| trunc(1.5):', Math.trunc(1.5));
const v = -0.4;
console.log('round(-0.4):', Math.round(v), '| Object.is(-0):', Object.is(Math.round(v), -0));
console.log('التقريب المتماثل:', Math.sign(-1.5) * Math.round(Math.abs(-1.5)));
console.log('JSON للناقص صفر:', JSON.stringify(Math.round(v)));التمرين
قرّب -2.5 و2.5 بـround وtrunc وfloor، وسجّل الفرق، وبعدين اكتب تقريب متماثل لـ-2.5.
جرّب بنفسك قبل ما تروح للدرس اللي بعده.
اتجرّب على Node v26.14.0 · آخر تشغيل