Thanks, I didn't know that but it makes sense now I think about it.
There's no "floor" command in DBC so I wrote my own rounding function, this way it works for negative values too.
sync on
rem Fraction to Decimal converter by OBese87
print "This program displays decimal numbers as fractions."
sync
DO
repeat
input "Enter a decimal> "; f#
until (f# <> 0.0)
whole = int(f#)
f# = f#-whole
for b = 1 to 1000
a# = b*f#
if abs(a# - round2int(a#)) < 0.0001 then exit
next b
if b > 1000
print "Conversion failed!"
else
frac$ = ""
if whole > 0 then frac$ = frac$+str$(whole)+" "
frac$ = frac$ + str$(round2int(a#))+"/"+str$(b)
print " = "; frac$
endif
sync
LOOP
rem ==========================================================
rem = Functions
rem ==========================================================
function round2int(n#)
n = int(n#+n#) - int(n#)
endfunction n
I was wondering how to write this as a function, how would I return a single value? I decided to return a string and found a useful side-effect of the val() command: it returns the numbers up to the first non-numerical character, in our case the numerator of our fraction. So converting a string back to a decimal is fairly simple, I just have to grab the denominator (length of the entire string - length of the numerator - one to drop the slash). Of course this means I will have to allow top-heavy fractions as a space would mess up the val() conversion. This is fine though, it's a more flexible way of doing it and you can remove the integer, prior to conversion, quite simply by
n#-int(n#). (Sometimes top-heavy fractions are even preferred.)
rem Fraction to Decimal converter by OBese87
sync on
sync
iter=0
n#=0.5
rem ==========================================================
rem = Main
rem ==========================================================
do
cls
print "This program converts decimal numbers to fractions and back again."
print "Enter a decimal number:>"
sync
for iter = 0 to 4
f$ = dec2frac$(n#)
print n#; " = "; f$
print "converted back to a decimal number:"; frac2dec(f$)
sync
input n#
next iter
loop
rem ==========================================================
rem = Functions
rem ==========================================================
function dec2frac$(dec#)
for b = 1 to 1000
a# = b*dec#
a = round2int(a#)
if abs(a# - a) < 0.0001 then exit
next b
if b > 1000
exitfunction "conversion failed!"
else
frac$ = str$(a)+"/"+str$(b)
endif
endfunction frac$
`//
function round2int(n#)
n = int(n#+n#) - int(n#)
endfunction n
`//
function frac2dec(a$)
num# = val(a$)
a$ = right$(a$, len(a$)-len(str$(num#))-1)
den# = val(a$)
endfunction num#/den#
[edit: code updated]
WARNING: The above comment may contain sarcasm.