0

Hello I would like to know how to get my NSString to to read 5.11 as 5.11 not 5.1. It is necessery that I can do this is that I am reading in from this field as feet and inches and not decimal format. This code works for the calculation

    CGFloat hInInches = [height floatValue];
    CGFloat hInCms = hInInches *0.393700787;
    CGFloat decimalHeight = hInInches;
    NSInteger feet = (int)decimalHeight;
    CGFloat feetToInch = feet*12;
    CGFloat fractionHeight = decimalHeight - feet;
    NSInteger inches = (int)(12.0 * fractionHeight);
    CGFloat allInInches = feetToInch + inches;
    CGFloat hInFeet = allInInches; 

But it doesnt let you read in the value taken from an nstextfield the right way.

Any help getting this to read in the right information from the nstextfield would be appreciated. Thanking You

AlanF
  • 1,591
  • 3
  • 14
  • 20
  • 2
    Where's any code here that handles strings? I don't see any relevance of the posted code. – Eiko Oct 17 '12 at 11:30

2 Answers2

0

You can call doubleValue method of string to get a precise value.

NSString *text = textField.text;
double value = [text doubleValue];
basar
  • 983
  • 9
  • 16
0

If I'm understanding this right, what you want to do is have a user enter "5.11" in an input that gets read as an NSString, and you want it to mean "5 feet 11 inches" rather than "5 feet plus 0.11 feet" (about 5 foot 1).

As a side note, I'd advise against this from a UI perspective. That being said...if you want to do it this way, the easiest way to get the values you want for "feet" and "inches" is to get them directly from the NSString instead of waiting until after you've converted them to numbers. A float is NOT a precise value, and you can run into problems down the road if you try to pretend a float is two integers on either side of a decimal.

Instead, try this:

NSString* rawString = [MyNSTextField stringValue]; // "5.11"
NSInteger feet;
NSInteger inches;

// Find the position of the decimal point

NSRange decimalPointRange = [rawString rangeOfString:@"."];

// If there is no decimal point, treat the string as an integer

if(decimalPointRange.location == NSNotFound) {
    {
    feet = [rawString integerValue];
    inches = 0;
    }

// If there is a decimal point, split the string into two strings, 
// one before and one after the decimal point

else
    {
    feet = [[rawString substringToIndex:decimalPointRange.location] integerValue];
    inches = [[rawString substringFromIndex:(decimalPointRange.location + 1)] integerValue];
    }

You now have integer values for feet and inches, and the rest of the conversions you want to do are trivial from that point:

NSInteger heightInInches = feet + (inches * 12);
CGFloat heightInCentimeters = (heightInInches * 2.54);
chapka
  • 490
  • 1
  • 3
  • 11