Why does converting a decimal number to an integer drop the fractional part?
Quick answer
A decimal’s fractional part disappears when the conversion operation discards it, but “convert to integer” does not specify one universal rule. In JavaScript, Math.trunc() removes fractional digits toward zero, while Math.round() selects the nearest integer, with exact halves going toward positive infinity. Other operations or languages may behave differently or reject the input. Identify the exact operation and test positive, negative, and halfway values.
The question, the details, the next step.
A practical checklist
Record the exact conversion function, operator, or input-reading method.
Test a positive decimal and a negative decimal, such as 13.8 and −13.8.
If you expect rounding, test an exact halfway value such as 5.5 and check the documented tie rule.
Compare each result with the operation’s documentation rather than assuming all integer conversions behave alike.
If the operation errors, note the input, its type, and the complete error message, then check that operation’s invalid-input behavior.
A few more useful answers
Does truncation always mean rounding down?
No. In JavaScript, Math.trunc() moves toward zero, so −13.8 becomes −13. That is different from always choosing the lower integer. [S1]
Does every language round halfway values the same way?
No. JavaScript Math.round() sends exact halves toward positive infinity; do not assume another language or operation uses that rule. Check its documentation. [S2]
Are bitwise shortcuts a safe substitute for Math.trunc() in JavaScript?
Not in all cases. MDN notes that bitwise shortcuts convert to 32-bit integers and can overflow, so use the documented operation that matches your intent. [S1]
Sources
References used for this guide.
- [S1] Math.trunc() — JavaScript | MDN developer.mozilla.org · Checked
- [S2] Math.round() — JavaScript | MDN developer.mozilla.org · Checked
