0

こんにちは私はNSStringに5.11を5.1ではなく5.11として読み取る方法を知りたいです。これができる必要があるのは、このフィールドから10進数形式ではなく、フィートとインチとして読み込んでいることです。このコードは計算に使用できます

    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から正しい情報を読み取るためにこれを取得するための助けをいただければ幸いです。ありがとう

4

2 に答える 2

0

私がこの権利を理解している場合、あなたがしたいのは、NSStringとして読み取られる入力にユーザーに「5.11」を入力させ、「5フィートプラス0.11」ではなく「5フィート11インチ」を意味するようにすることです。フィート」(約5フィート1)。

ちなみに、UIの観点からはこれに反対することをお勧めします。そうは言っても...このようにしたい場合、「フィート」と「インチ」に必要な値を取得する最も簡単な方法は、変換するまで待つのではなく、NSStringから直接取得することです。数字に。浮動小数点数は正確な値ではありません。浮動小数点数が小数の両側に2つの整数であると偽ってみると、問題が発生する可能性があります。

代わりに、これを試してください:

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);
于 2012-10-17T13:29:16.233 に答える
0

文字列の doubleValue メソッドを呼び出して、正確な値を取得できます。

NSString *text = textField.text;
double value = [text doubleValue];
于 2012-10-17T11:31:46.383 に答える