|
Does anyone have an example of converting a decimal number to it's fractional equivalent?
For example: 15.3750 = 15-3/8
The decimal field to convert is a 10/4 field. Any help is appreciated. Thanks in advance!
BTW, this particular program outputs:
> call fract
DSPLY 123 57/125
DSPLY 123
DSPLY 123 17/50
DSPLY 123 1929/15625
DSPLY 123 4/5
DSPLY 123 1/8............................................................
H dftactgrp(*no) bnddir('QC2LE')D fraction pr 50a varying
D numstr 50a varying value
/free
dsply (fraction('123.4560'));
dsply (fraction('123.0000'));
dsply (fraction('123.34'));
dsply (fraction('123.123456'));
dsply (fraction('123.8'));
dsply (fraction('123.125'));
*inlr = *on;
/end-free //--------------------------------------------------------------
// Procedure: fraction
//--------------------------------------------------------------
// Convert number string from decimal to fractional form.
//
// Parameters:
// I: numstr -- string representing decimal numeric value
//
// Returns:
// String of number in reduced fractional form.
//--------------------------------------------------------------
P fraction b
D fraction pi 50a varying
D numstr 50a varying value
D atoi pr 10i 0 extproc('atoi')
D str * value options(*string)
D int s 10i 0
D dec s 10i 0 inz(0)
D decpos s 10i 0
D numerator s 10i 0
D denominator s 10i 0
D factor s 10i 0
/free
// slough trailing blanks and zeros in number string
dow %subst(numstr:%len(numstr):1) = ' '
or %subst(numstr:%len(numstr):1) = '0';
%len(numstr) = %len(numstr) - 1;
enddo; // find decimal point
decpos = %scan('.':numstr); // return now if we don't have decimal digits
if decpos = 0;
return numstr;
elseif decpos = %len(numstr);
return %subst(numstr:1:decpos-1);
endif;// find digits to the left and right of the decimal point int = atoi (%subst(numstr:1:decpos-1)); dec = atoi (%subst(numstr:decpos+1));
// determine numerator and denominator numerator = dec; denominator = %inth(10**(%len(numstr)-decpos));
// reduce fraction to smallest possible numerator/denominator
for factor = 2 to %div(denominator:2);
dow %rem(numerator:factor) = 0
and %rem(denominator:factor) = 0;
numerator = %div(numerator:factor);
denominator = %div(denominator:factor);
enddo;
endfor; // return fractional string
return %char(int) + ' ' + %char(numerator)
+ '/' + %char(denominator);
/end-free
P fraction e
............................................................As an Amazon Associate we earn from qualifying purchases.
This mailing list archive is Copyright 1997-2025 by midrange.com and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available on our policy page. If you have questions about this, please contact [javascript protected email address].
Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.