Question

Yes I have seen This question But it's for php. I'm still new to programming and was surprised there wasn't a iOS question posted for this. This is how I'm converting from decimal to fraction. Thought it may help with the formatting for Imperial to Metric. So the question is how would I go about converting from imperial to metric in iOS?

//Converts Decimals to Fractions.
- (NSString *)DecToFrac:(float)input {

NSArray * array = [[NSArray alloc] initWithObjects: @"",@"",@"1/8",@"",@"1/4",@"",@"3/8",@"",@"1/2",@"",@"5/8",@"",@"3/4",@"",@"3/4",@"",@"7/8",@"",nil];

int fractions = lroundf((input - (int)input)/((float)1/(float)16));
if(fractions == 0 || fractions == 16) {
    return [NSString stringWithFormat:@"%d''",lroundf(input)];
} else {
    if([[array objectAtIndex:fractions] isEqualToString:@""]) {
        return [NSString stringWithFormat:@"%d %d/16''",(int)input,fractions];
    } else {
        return [NSString stringWithFormat:@"%d %@''",(int)input,[array objectAtIndex:fractions]];
    }
}

}
Was it helpful?

Solution

Because most conversions are simply arithmetic problems, iOS should be able to handle anything you give it just fine. To use my example of inches to centimeters maybe try:

-(float)centimetersToInches:(float)centimeters {
    float inches = centimeters/2.54;
    return inches;
}

Everything else is a matter of storing which formula goes with which pairing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top