Sign in to follow this  
Followers 0
erifash

Decimal To Fraction

3 posts in this topic

#1 ·  Posted (edited)

I have created a function that takes a non-integer (float) and turns it into a fraction. If anyone is interested then check out this code:

; Useage - D2F( decimal number )
; Return - one dimensional array with two elements:
; element[0] = numerator
; element[1] = denominator
; On failure it will set @error to 1 and return a blank string.

Func D2F( $dec )
    If IsInt($dec) Then
        SetError(1)
        Return ""
    EndIf
    Local $i = 1, $bNeg = ($dec < 0), $f[2]
    If $bNeg Then $dec *= -1
    Do
        $i += 1
        $f[0] = $dec * $i
    Until IsInt($f[0])
    If $bNeg Then $f[0] *= -1
    $f[1] = $i
    Return $f
EndFunc
It can also simplify a fraction, as shown in this example:
$n = 28
$d = 44

$f = $n / $d
$a = D2F($f)

If @error Then Exit
MsgBox(0, $f, $a[0] & @CRLF & $a[1]); Would return 7/11 instead of 28/44

Any comments/questions are greatly appreciated! B)

Edited by erifash

Share this post


Link to post
Share on other sites



I have created a function that takes a non-integer (float) and turns it into a fraction. If anyone is interested then check out this code:

; Useage - D2F( decimal number )
; Return - one dimensional array with two elements:
; element[0] = numerator
; element[1] = denominator
; On failure it will set @error to 1 and return a blank string.

Func D2F( $dec )
    If IsInt($dec) Then
        SetError(1)
        Return ""
    EndIf
    Local $i = 1, $bNeg = ($dec < 0), $f[2]
    If $bNeg Then $dec *= -1
    Do
        $i += 1
        $f[0] = $dec * $i
    Until IsInt($f[0])
    If $bNeg Then $f[0] *= -1
    $f[1] = $i
    Return $f
EndFunc
It can also simplify a fraction, as shown in this example:
$n = 28
$d = 44

$f = $n / $d
$a = D2F($f)

If @error Then Exit
MsgBox(0, $f, $a[0] & @CRLF & $a[1])

Any comments/questions are greatly appreciated! B)

This is great. It could be very usefull for some one who deals with large floats in their script. Just out of curiousity did you just do this for the fun on it or is it part of a larger project? I feel like most people will not see the greatness of your function but to some one who needs it, it will be a treasured.

Share this post


Link to post
Share on other sites

Thanks! Yeah, it is just a little thing I wanted to do. My calculator (TI-83+) has a function to convert a decimal to a fraction so I thought, "If a simple calculator can do it, why can't AutoIt?" B)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0