Objective c NSC字符串输入转换目标

Objective c NSC字符串输入转换目标,objective-c,nsstring,decimal,nstextfield,Objective C,Nsstring,Decimal,Nstextfield,您好,我想知道如何让我的NSString将5.11理解为5.11而不是5.1。 这是必要的,我可以做到这一点是,我从这个领域阅读英尺和英寸,而不是十进制格式。此代码适用于计算 CGFloat hInInches = [height floatValue]; CGFloat hInCms = hInInches *0.393700787; CGFloat decimalHeight = hInInches; NSInteger feet = (int)decimal

您好,我想知道如何让我的NSString将5.11理解为5.11而不是5.1。 这是必要的,我可以做到这一点是,我从这个领域阅读英尺和英寸,而不是十进制格式。此代码适用于计算

    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; 
但它不允许您以正确的方式读取从nstextfield获取的值

如果您能从nstextfield获取正确的信息,我们将不胜感激。
谢谢

您可以调用字符串的doubleValue方法来获得精确的值

NSString *text = textField.text;
double value = [text doubleValue];

如果我理解正确,你要做的是让用户在一个输入中输入“5.11”,然后作为NSString读取,你希望它的意思是“5英尺11英寸”,而不是“5英尺加0.11英尺”(大约5英尺1)

作为补充说明,我建议从用户界面的角度反对这种做法。也就是说,如果您想这样做,获取“英尺”和“英寸”值的最简单方法是直接从NSString中获取它们,而不是等到将它们转换为数字后再获取。浮点不是一个精确的值,如果你试图假装一个浮点是十进制两边的两个整数,你可能会遇到问题

相反,请尝试以下方法:

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];
    }
现在,英尺和英寸都有整数值,从这一点开始,要进行的其余转换都很简单:

NSInteger heightInInches = feet + (inches * 12);
CGFloat heightInCentimeters = (heightInInches * 2.54);

这里哪里有处理字符串的代码?我看不出发布的代码有任何关联。