Reputation: 189
I am trying to round to the nearest whole number for my assignment in assembly language and I've been spinning my wheels trying to figure it out. If for example I perform a division function 137/6, how do I get the result to round to the nearest whole number?
Upvotes: 0
Views: 3320
Reputation: 34585
For positive values add half the denominator to the numerator before the division. I leave the more complex situation of negative values to you.
mov ecx, [denominator] ; divisor
mov eax, ecx ; copy to numerator register
shr eax, 1 ; half divisor
add eax, [numerator] ; add to numerator
div ecx ; (numerator + denominator/2) / denominator
Upvotes: 3
Reputation: 14409
"Round half towards positive infinity" for a positive number (explanations in the comments):
xor edx, edx ; Clear EDX for division
mov eax, [numerator] ; Dividend stored in the data section (eg. dd 137)
mov ecx, [denominator] ; Divisor stored in the data section (eg. dd 6)
div ecx ; EDX:EAX / ECX = EAX remainder EDX
shl edx, 1 ; EDX *= 2
cmp edx, ecx ; Fraction part < 0.5 (remainder*2 < divisor) ?
jb .done ; Yes: skip rounding
add eax, 1 ; No: round half up (http://en.wikipedia.org/wiki/Rounding#Round_half_up)
.done: ; EAX = rounded result of division
Upvotes: 2