【问题标题】:NSString input conversion objective cNSString输入转换目标c
【发布时间】:2012-10-17 11:23:44
【问题描述】:

您好,我想知道如何让我的 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 读取正确信息,我们将不胜感激。 谢谢你

【问题讨论】:

  • 这里有处理字符串的代码吗?我没有看到发布的代码有任何相关性。

标签: objective-c nsstring decimal nstextfield


【解决方案1】:

你可以调用字符串的doubleValue方法来得到一个精确的值。

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

【讨论】:

    【解决方案2】:

    如果我的理解正确,您想要做的是让用户在输入中输入“5.11”,该输入被读取为 NSString,并且您希望它的意思是“5 英尺 11 英寸”而不是“5英尺加 0.11 英尺”(约 5 英尺 1)。

    作为旁注,我建议从 UI 的角度不要这样做。话虽这么说...如果您想这样做,获取“英尺”和“英寸”值的最简单方法是直接从 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多