Now, be rational
A common need in financial programming is to convert from the computer form of a number to a human-readable form. For example, one might need to convert stock prices. If prices are carried inside a computer as real numbers, it is necessary to convert them to fractional form for display. A reader of the stock page of a newpaper wants to see 5 13/16 as the high of the day, not 5.8125 . A convenient way to do this is to separate the number into its whole number part and its fractional part, and then convert the fractional part into numerator and denominator of a rational number less than 1 . Using parts=.0 1&#: to obtain the whole number and fractional parts, a verb to convert the fractional part into numerator and denominator is nd , show below: ] 'w f'=.parts 5.8125 5 0.8125 f 0.8125 nd=.(,%+.)&1 nd f 13 16 It works for complex fractional parts, too: nd 0.8125j0.5 13j8 16 The verb works by appending (,) a 1 to the fractional part, giving 0.8125 1 , finding the gcd (+.) of the number and 1 , giving 0.0625 , and dividing (%) this into the pair of numbers, giving 13 16 . |