开发者

objective-c converting strings to usable numbers

I have strings that look about like this:

stringA = @"29.88";开发者_C百科
stringB = @"2564";
stringC = @"12";
stringD = @"-2";

what is the best way to convert them so they can all be used in the same mathmatical formula?? that includes add, subtract.multiply,divide etc


Probably floatValue (as it appears you want floating-point values), though integerValue may also be of use (both are instance methods of NSString).


[stringA doubleValue]


These are all wrong, because they don't handle errors well. You really want an NSNumberFormatter.

If you have the string @"abc" and try to use intValue or floatValue on it, you'll get 0.0, which is obviously incorrect. If you parse it with an NSNumberFormatter, you'll get nil, which is very easy to distinguish from an NSNumber (which is what would be returned if it was able to parse a number).


Assuming that you have NSString variables.

NSString *stringA = @"29.88";
NSString *stringB = @"2564";
NSString *stringC = @"12";
NSString *stringD = @"-2";

suppose, you want to convert a string value to float value, use following statement.

float x=[stringA floatValue];

suppose, you want to convert a string value to integer value, use following statement.

NSInteger y = [stringC intValue];

Hope, it helps to you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜