Fractions to decimals is easy. Decimals to fractions is a bit harder (and

many decimal values will not reduce much) - but if you consider (say) 0.875

to be 875/1000 then all you need to do is reduce this fraction. Some months

ago Bart Lateur posted some code to do exactly this - and I am sure that he

will not mind me reproducing it here:

Subject: Re: Working with fractions

Date: 29 October 1998 22:20

If we represent a fraction by two (long) integers, T and B (for Top and

Bottom; I find the official names a bit too difficult); then you can

reduce this fraction "T/B" by dividing T and B by their GCD (greatest

common divisor).

For example: "14/21", the GCD of 14 and 21 is 7, so we do T/7 and B/7

resulting in "2/3".

The GCD can easiliy be calculated using Euclid's method (see

<http://www.cut-the-knot.com/blue/binary.html> for a mathemaical proof):

To calculate the GCD of two positive numbers M and N:

* divide the large number by the smaller; we only need the remainder;

* if the remainder is zero, the smaller number is the GCD;

* if it's not, replace the larger number by the smaller, and the

smaller by the remainder. Repeat until the remainder IS zero.

Example: 14 and 21. 21 mod 14 is 7; 14 mod 7 is 0. Therefore, the GCD is

7.

Special care must be taken if either Top or Bottom are negative.

Here's some code.

Function gcd (ByVal m&, ByVal n&) As Long

'm and n must be > 0

Dim temp&

If m < n Then temp = m: m = n: n = temp

Do

temp = m Mod n

If temp = 0 Then Exit Do

m = n

n = temp

Loop

gcd = n

End Function

Function fraction (ByVal t&, ByVal b&) As String

Dim c&, sign%

If b < 0 Then t = -t: b = -b

c = gcd(Abs(t), Abs(b))

If c = b Then

fraction = CStr(t / b)

Else

fraction = CStr(t / c) & "/" & CStr(b / c)

End If

End Function

You could improve on the representation, for T > B, by splitting of the

integer part. Hint: you need Cstr(int(T/B)) and

Cstr(T mod B) & "/" & Cstr(B)

Mike

Quote:

>Are there any good routines for converting fractions to decimal numbers and

>decimal numbers to fractions