Round 'n Round We Go!

Published Monday, August 13, 2007 11:40 AM

After a year I posted my rounding question in the forums, I finally got it working. Here's the original post I made; http://devpinoy.org/forums/t/915.aspx.

Just this morning, I had nothing to do, so I excavated some of my unsolved sources from my archive. Then I remembered this problem about rounding stuff in assembly. I thought, maybe it's time to solve this, so I did.

The original problem I had was I did not know how to round to a specified number of digits. For example, I have the value 3.1456825863, which I wanted to round to 3 decimal places like this 3.146. For my original code, it always outputs 3. Then it hit me! I already had this problem in flash before, the function Math.round does the same thing, but I already solved it there. So again, excavated the FLA project... and the rest was rounding history. So here's the code using the FPU.

01     .586
02
03     ...
04
05     .data
06     buffer   db    1024 dup(0)
07     fbuffer  dq    0
08     pi        dq    3.14
09     rdigit    dq   10000.0
10
11     ...
12
13     .code
14
15     ...
16
17     invoke GetDlgItemText, hWin, IDC_EDIT_INPUT, addr buffer, SIZEOF buffer
18     invoke StrToFloat, addr buffer, addr fbuffer   
19            fld         fbuffer
20            fmul      pi
21            fmul      rdigit
22            frndint   
23            fdiv        rdigit
24            fstp       fbuffer
25     invoke FloatToStr2, fbuffer, addr buffer
26     invoke SetDlgItemText, hWin, IDC_EDIT_OUTPUT, addr buffer
27
28     ...
29
30     end start

The most important parts for this are lines 09, 21, 22, and 23. Line 09 (rdigit) is the one responsible for controlling the number of significant digits to be displayed, depending on the number of zeroes in it. Example, the input is 3.1456825863 and rdigit is 100.0, the output will be 3.15, since there are 2 zeroes in 100 (My code above will output 3.1457). Lines 21 to 23 simply means that Math.round(ST(0)*rdigit)/rdigit), which is responsible for doing the trick.

So there it is, I hope this helps anyone who will encounter this problem. Please feel free to comment if there are errors in this. I tested it with my scenarios and it worked like a charm, but who knows...

Yes Creds goes out to cvega for the help I got with this piece. Thanks!

by modchip

Comments

# lamia said on Sunday, August 12, 2007 10:57 PM

Magaling, magaling, magaling! :)

# super said on Monday, August 13, 2007 12:43 AM

great :D

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: