开发者

Objective C - Number to String and Grab length inconsistencies

I am trying to grab a number from a text box entry, convert it to string and grab the length of it. (IE: Perform a LEN(someInteger) on a number).

I have been able to get it working, however there are some inconsistencies when the number is 0 or null.

For example;

-(IBAction)update
{
   // inputField is the number pad textbox
   double myInput = [inputField.text doubleValue];

   // 
   NSNumber *c = [NSNumber numberWithDouble:myInput];
   NSString *myOutput  = [c stringValue];

   NSLog(@"Starting number (number) = %@", c);
   NSLog(@"myOutput (string) = %@", myOutput);
   NSLog(@"myOutput (length) = %d", ([myOutput length]) );

}

The conversion for number to string works fine. The problem I have is with the length, especially when there are no numbers (or null) entry.

I have a number pad text box entry on an XIB which has a "text" of 0 (the placeholder just says "Enter number here")

When you first start typing into the text box the "text" goes away and you start with a blank text box.

Problem 1 -- when you first enter the text box there is nothing in the textbox, but my NSLog says the output length is 1 character long.

This causes a problem because visually there is nothing in the textbox but the [myOutput length] reports 1 character length.

Problem 2 -- when you start to enter numbers, everything goes well -- but when you start to remove numbers to the point where you clear the text box completely it reports a length of 1 character.

How can it read 1 character long if there is nothing in the text box? I think it must be the "text" (From identity inspector) again.

Summary.

  1. There is a number pad text box entry field. Whenever you update the entry, it calls the IBaction update method.

  2. When you first enter numbers into the text box there is nothing visually displayed in the input field, but the NSLog reports the length is 1 character long.

  3. When you start entering numbers and then start to remove them one at a time till you completely remove all numbers it repo开发者_如何学JAVArts the length as being 1 character long.

In both cases the NSLog should be reporting 0 length, but it never does. I tried doing [myOutput length] - 1 but this gives me weird results.

Any help on this would be great

Thanks.


If there's no text, myInput will be equal to 0.0. myOutput will then be equal to @"0", which has a length of 1.

Why not just use [inputField.text length]?

You could do something like this:

NSNumber *number = nil;
if ([inputField.text length] > 0) {
    number = [NSNumber numberWithDouble:[inputField.text doubleValue]];
}

That way you have your number if it exists, otherwise number will be nil.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜