How to round numbers to a specific number of dp

This code will show you how to round numbers in QBasic.

Firstly, a bit of background.

QBasic works with a DOUBLE data type by default. What this means is that sometimes numbers that your ordinary calculator can handle easily do not get displayed correctly in Qbasic. Here is an example:

CLS

PRINT 10 - 1.94

Now run the program, and you will see what I mean. QBasic sees the 1.94 and has a hangover when it tries to convert it to binary. The result of the code is:

1.111010100111010100101001.

Why? QB doesn't waste the time to calculate the correct values of zero (0) for the other spaces.

Here's a non-hangover result:

CLS

PRINT 10# - 1.94#

Two rounding function solutions:

FUNCTION round# (num AS DOUBLE, dp AS INTEGER)

'WARNING: USE "#" at the end of constant values,

'or else you will get rounding errors:

' "num = .45" >> "num = .449999988079071

' "num = .45#" >> "num = .45"

DIM exp1 AS LONG, num2 AS LONG

exp1 = 10 ^ dp: num2 = num * exp1: round# = num2 / exp1

PRINT num

END FUNCTION

*OR*

FUNCTION round (num, dp)

'WARNING: USE "#" at the end of constant values,

'or else you will get rounding errors:

' "num = .45" >> "num = .449999988079071

' "num = .45#" >> "num = .45"

DIM n AS DOUBLE, exp AS DOUBLE

exp = (10 ^ dp): n = num * exp

IF n >= 0 THEN

n = SGN(n) * (ABS(INT(n + .5)))

ELSE

n = SGN(n) * (ABS(INT(n - .5)))

END IF

round = n / exp

END FUNCTION

Example program using this function:

num# = 12.3892#

dp = 2

decplaces = round(num#, dp)

credit: Oracle, Moneo, Agamemnus

RoundingNumbers - page last edited 2004-03-27 11:19:42 by 172.151.106.223 (home) (edit)

Blast WIKI - by RoboticBoy - edited and tweaked for our evil purposes by Hexadecimal Disaster

Blast WIKI - by RoboticBoy - edited and tweaked for our evil purposes by Hexadecimal Disaster