2

Need help to display number with decimal places in assembly language using visual studio .asm file.
For instance, 10 divide 4 will be 2.5 but it only displays 2

mov eax, 10
mov ebx, 4
xor edx, edx
div ebx
call WriteDec
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
CW_2434
  • 156
  • 10
  • Show your attempts to solve? – funnydman Dec 23 '19 at 07:12
  • Is `WriteDec` from Irvines library? – rkhb Dec 23 '19 at 07:47
  • 1
    Yes, that's how integer division works. Your options include fixed-point (@shift_left's answer), floating-point (usually with hardware FP, like converting to FP and using a `divsd` instruction), and arbitrary / extended precision and/or keeping track of fractions and only converting to a decimal string if needed. – Peter Cordes Dec 23 '19 at 16:34

2 Answers2

4

DIV offers as result both the integer quotient and the remainder. From the remainder you can construct an integer number after the decimal point by multiplying it by 10 and dividing it by the divisor:

INCLUDE Irvine32.inc

.CODE

main PROC
    mov eax, 10             ; Dividend
    mov ebx, 4              ; Divisor
    xor edx, edx            ; High 32 bit of dividend
    div ebx                 ; Result: EAX, remainder in EDX
    call WriteDec           ; http://programming.msjc.edu/asm/help/index.html?page=source%2Firvinelib%2Fwritedec.htm

    mov al, '.'             ; Decimal point
    call WriteChar          ; http://programming.msjc.edu/asm/help/index.html?page=source%2Firvinelib%2Fwritechar.htm

    imul eax, edx, 10       ; EAX = EDX * 10 i.e. New dividend = Old remainder * 10
    xor edx, edx            ; Clear the high part of dividend
    div ebx                 ; EAX rem. EDX = EDX:EAX / EBX
    call WriteDec           ; http://programming.msjc.edu/asm/help/index.html?page=source%2Firvinelib%2Fwritedec.htm

    exit
main ENDP

END main

Depending on the desired number of decimal places, you can repeat this procedure.

rkhb
  • 14,159
  • 7
  • 32
  • 60
1

Skew the dividend by the number of decimal places you want. So 100 / 4 = 25 or if you want something like 10 / 4.5 = 2.22 then you would take 10000 / 45 = 222 and your algorithm to display the value just needs to insert decimal in the proper place.

Shift_Left
  • 1,208
  • 8
  • 17