One approach would be to have them enter the data as a string, and then search the string for a "slash" character. Everything before the slash is assumed to be the numerator, everything afterwards becomes the denominator. You'd then convert each to integers and do the math, storing the result in a double.
Error handling could be a bit tricky - you'd have to catch the jokers who enter stuff like "1/0", "2/-3", ".4/10", etc.
I thought of that, but decided it was too much managing for a simple number.
Instead I have three numeric controls (the old fashioned way) one for Whole Num, one for Numerator, and one for Denominator. For any text boxes that only display the number I put in a quick function that rounds the number to the nearest 64th (dealing in inches and we never go below a 64th) and shows the appropriate fraction.
Both the way I handled it and your suggestion are very loose and I should probably build a custom control that accounts for all possibilties. However, I envy non-American Standard industries and other nations as decimals are much MUCH easier for them to convert (e.g. millimeters, centimeters,etc..). I guess that goes to show that stubborness CAN come back around and bite ya in the rear!
Hmmm. You've got a constrained set of values that have domain application (measuring stuff in fractions of an inch) that the user shouldn't go outside of. So how about a drop-down list?
if you want to turn a decimal into a fraction then try this:
1) take the decimal (d) and count its decimal places . d = 0.3168, n = 4. (you can just set n to something that is pleanty large enough if you want).
2) create a fraction thus - d*(10^n)/10^n. 3168/10000.
3) find the Highest Common Multiple of the numerator and the denominator. to do this you will need a for loop (i) that goes from 1 to the ceiling of the square root of the numerator (you're not going to find a hcm hgher than this, assuming d<=1). test each number by dividing both the numerator and the denominator by i; if both results are whole numbers, then you have found a common multiple - the last one you find will be the highest.
4) divide top and bottom by the hcm. 198/625, perhaps.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.