如何将 NSString 转换为 NSNumber

发布于 2024-08-05 09:10:48 字数 444 浏览 9 评论 0原文

如何转换包含许多任何原始数据类型的 NSString (例如 intfloatcharunsigned int 等)?问题是,我不知道字符串在运行时将包含哪种数字类型。

我知道如何做到这一点,但我不确定这是否适用于任何类型,也适用于无符号和浮点值:

long long scannedNumber;
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanLongLong:&scannedNumber]; 
NSNumber *number = [NSNumber numberWithLongLong: scannedNumber];

感谢您的帮助。

How can I convert a NSString containing a number of any primitive data type (e.g. int, float, char, unsigned int, etc.)? The problem is, I don't know which number type the string will contain at runtime.

I have an idea how to do it, but I'm not sure if this works with any type, also unsigned and floating point values:

long long scannedNumber;
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanLongLong:&scannedNumber]; 
NSNumber *number = [NSNumber numberWithLongLong: scannedNumber];

Thanks for the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

只想待在家 2024-08-12 09:10:48

使用 NSNumberFormatter

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:@"42"];

如果字符串不是有效数字,则 myNumber 将为 nil。如果它是一个有效的数字,那么您现在就可以利用 NSNumber 的优点来确定它实际上是什么类型的数字。

Use an NSNumberFormatter:

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:@"42"];

If the string is not a valid number, then myNumber will be nil. If it is a valid number, then you now have all of the NSNumber goodness to figure out what kind of number it actually is.

流年里的时光 2024-08-12 09:10:48

您可以使用 -[NSString integerValue]-[NSString floatValue] 等。但是,正确的(区域设置敏感等)方法是使用-[NSNumberFormatter numberFromString:] 它将为您提供一个从适当的语言环境转换而来的 NSNumber,并给出 NSNumberFormatter 的设置(包括是否允许浮点值)。

You can use -[NSString integerValue], -[NSString floatValue], etc. However, the correct (locale-sensitive, etc.) way to do this is to use -[NSNumberFormatter numberFromString:] which will give you an NSNumber converted from the appropriate locale and given the settings of the NSNumberFormatter (including whether it will allow floating point values).

用心笑 2024-08-12 09:10:48

Objective-C

(注意:此方法在不同的语言环境中表现不佳,但比 NSNumberFormatter 稍快)

NSNumber *num1 = @([@"42" intValue]);
NSNumber *num2 = @([@"42.42" floatValue]);

Swift

简单但肮脏的方式

// Swift 1.2
if let intValue = "42".toInt() {
    let number1 = NSNumber(integer:intValue)
}

// Swift 2.0
let number2 = Int("42")

// Swift 3.0
NSDecimalNumber(string: "42.42") 

// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)

扩展 -方式
这实际上更好,因为它可以很好地处理区域设置和小数。

extension String {
    
    var numberValue:NSNumber? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter.number(from: self)
    }
}

现在您可以简单地执行以下操作:

let someFloat = "42.42".numberValue
let someInt = "42".numberValue

Objective-C

(Note: this method doesn't play nice with difference locales, but is slightly faster than a NSNumberFormatter)

NSNumber *num1 = @([@"42" intValue]);
NSNumber *num2 = @([@"42.42" floatValue]);

Swift

Simple but dirty way

// Swift 1.2
if let intValue = "42".toInt() {
    let number1 = NSNumber(integer:intValue)
}

// Swift 2.0
let number2 = Int("42")

// Swift 3.0
NSDecimalNumber(string: "42.42") 

// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)

The extension-way
This is better, really, because it'll play nicely with locales and decimals.

extension String {
    
    var numberValue:NSNumber? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter.number(from: self)
    }
}

Now you can simply do:

let someFloat = "42.42".numberValue
let someInt = "42".numberValue
紅太極 2024-08-12 09:10:48

对于以整数开头的字符串,例如 @"123"@"456 ft"@"7.89" 等,请使用 < a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/integerValue" rel= “noreferrer”>-[NSString integerValue]

因此,@([@"12.8 lbs" integerValue]) 就像做 [NSNumber numberWithInteger:12] 一样。

For strings starting with integers, e.g., @"123", @"456 ft", @"7.89", etc., use -[NSString integerValue].

So, @([@"12.8 lbs" integerValue]) is like doing [NSNumber numberWithInteger:12].

寒尘 2024-08-12 09:10:48

你还可以这样做:

NSNumber *number = @([dictionary[@"id"] intValue]]);

玩得开心!

You can also do this:

NSNumber *number = @([dictionary[@"id"] intValue]]);

Have fun!

蓝眼泪 2024-08-12 09:10:48

如果您知道收到整数,则可以使用:

NSString* val = @"12";
[NSNumber numberWithInt:[val intValue]];

If you know that you receive integers, you could use:

NSString* val = @"12";
[NSNumber numberWithInt:[val intValue]];
荒人说梦 2024-08-12 09:10:48

这是 NSNumberFormatter 读取本地化数字 NSString (xCode 3.2.4, osX 10.6) 的工作示例,以节省其他人我刚刚花费的时间。请注意:虽然它可以处理尾随空格(“8,765.4”有效),但它不能处理前导空格,也不能处理杂散文本字符。 (错误的输入字符串:“8”和“8q”和“8 q”。)

NSString *tempStr = @"8,765.4";  
     // localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
     // next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial

NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(@"string '%@' gives NSNumber '%@' with intValue '%i'", 
    tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release];  // good citizen

Here's a working sample of NSNumberFormatter reading localized number NSString (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks ("8,765.4 " works), this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)

NSString *tempStr = @"8,765.4";  
     // localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
     // next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial

NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(@"string '%@' gives NSNumber '%@' with intValue '%i'", 
    tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release];  // good citizen
多彩岁月 2024-08-12 09:10:48

我想将字符串转换为双精度数。上面的答案对我来说不太有效。但这做到了:How to do string conversions in Objective-C?

我几乎所做的就是:

double myDouble = [myString doubleValue];

I wanted to convert a string to a double. This above answer didn't quite work for me. But this did: How to do string conversions in Objective-C?

All I pretty much did was:

double myDouble = [myString doubleValue];
才能让你更想念 2024-08-12 09:10:48

谢谢大家!我结合反馈,最终设法从文本输入(字符串)转换为整数。另外它可以告诉我输入是否是整数:)

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:thresholdInput.text];

int minThreshold = [myNumber intValue]; 

NSLog(@"Setting for minThreshold %i", minThreshold);

if ((int)minThreshold < 1 )
{
    NSLog(@"Not a number");
}
else
{
    NSLog(@"Setting for integer minThreshold %i", minThreshold);
}
[f release];

Thanks All! I am combined feedback and finally manage to convert from text input ( string ) to Integer. Plus it could tell me whether the input is integer :)

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:thresholdInput.text];

int minThreshold = [myNumber intValue]; 

NSLog(@"Setting for minThreshold %i", minThreshold);

if ((int)minThreshold < 1 )
{
    NSLog(@"Not a number");
}
else
{
    NSLog(@"Setting for integer minThreshold %i", minThreshold);
}
[f release];
雨巷深深 2024-08-12 09:10:48

我认为 NSDecimalNumber 会做到这一点:

示例:

NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];

NSDecimalNumber 是 NSNumber 的子类,因此允许隐式转换。

I think NSDecimalNumber will do it:

Example:

NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];

NSDecimalNumber is a subclass of NSNumber, so implicit casting allowed.

信愁 2024-08-12 09:10:48

C 的标准 atoi 怎么样?

int num = atoi([scannedNumber cStringUsingEncoding:NSUTF8StringEncoding]);

您认为有什么注意事项吗?

What about C's standard atoi?

int num = atoi([scannedNumber cStringUsingEncoding:NSUTF8StringEncoding]);

Do you think there are any caveats?

万劫不复 2024-08-12 09:10:48

您可以只使用 [string intValue][string floatValue][string doubleValue]

您也可以使用 NSNumberFormatter 类:

You can just use [string intValue] or [string floatValue] or [string doubleValue] etc

You can also use NSNumberFormatter class:

冰雪梦之恋 2024-08-12 09:10:48

你也可以这样做代码8.3.3 ios 10.3支持

[NSNumber numberWithInt:[@"put your string here" intValue]]

you can also do like this code 8.3.3 ios 10.3 support

[NSNumber numberWithInt:[@"put your string here" intValue]]
征棹 2024-08-12 09:10:48
NSDecimalNumber *myNumber = [NSDecimalNumber decimalNumberWithString:@"123.45"];
NSLog(@"My Number : %@",myNumber);
NSDecimalNumber *myNumber = [NSDecimalNumber decimalNumberWithString:@"123.45"];
NSLog(@"My Number : %@",myNumber);
黯然#的苍凉 2024-08-12 09:10:48

试试这个

NSNumber *yourNumber = [NSNumber numberWithLongLong:[yourString longLongValue]];

注意 - 我已经根据我的要求使用了 longLongValue 。您还可以根据您的要求使用integerValue、longValue 或任何其他格式。

Try this

NSNumber *yourNumber = [NSNumber numberWithLongLong:[yourString longLongValue]];

Note - I have used longLongValue as per my requirement. You can also use integerValue, longValue, or any other format depending upon your requirement.

束缚m 2024-08-12 09:10:48

工作于Swift 3

NSDecimalNumber(string: "Your string") 

Worked in Swift 3

NSDecimalNumber(string: "Your string") 
束缚m 2024-08-12 09:10:48

我知道这已经很晚了,但下面的代码对我有用。

尝试此代码

NSNumber *number = @([dictionary[@"keyValue"] intValue]]);

这可能会对您有所帮助。谢谢

I know this is very late but below code is working for me.

Try this code

NSNumber *number = @([dictionary[@"keyValue"] intValue]]);

This may help you. Thanks

七禾 2024-08-12 09:10:48
extension String {

    var numberValue:NSNumber? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter.number(from: self)
    }
}

let someFloat = "12.34".numberValue
extension String {

    var numberValue:NSNumber? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter.number(from: self)
    }
}

let someFloat = "12.34".numberValue
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文