Jak przekonwertować NSString na NSNumber

Jak mogę przekonwertować NSString zawierającą liczbę dowolnego prymitywnego typu danych (np. int, float, char, unsigned int, itd.)? Problem w tym, że nie wiem, który typ liczby będzie zawierać łańcuch w czasie wykonywania.

Mam pomysł, jak to zrobić, ale nie jestem pewien, czy to działa z dowolnym typem, również wartościami unsigned i zmiennoprzecinkowymi:

long long scannedNumber;
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanLongLong:&scannedNumber]; 
NSNumber *number = [NSNumber numberWithLongLong: scannedNumber];
Dzięki za pomoc.
Author: brynbodayle, 2009-09-19

18 answers

Użyj NSNumberFormatter:

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

Jeśli łańcuch znaków nie jest poprawną liczbą, to {[2] } będzie nil. Jeśli jest to prawidłowa liczba, to masz teraz wszystkie NSNumber dobroć, aby dowiedzieć się, jakiego rodzaju liczba to faktycznie jest.

 1204
Author: Dave DeLong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-18 16:01:30

Możesz użyć -[NSString integerValue], -[NSString floatValue], itd. Jednak poprawne (locale-sensitive, etc.) sposobem na to jest użycie -[NSNumberFormatter numberFromString:], które da Ci numer nsnumber przekonwertowany z odpowiedniego ustawienia lokalnego i biorąc pod uwagę ustawienia NSNumberFormatter (w tym, czy pozwoli na wartości zmiennoprzecinkowe).

 177
Author: Barry Wark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-19 16:24:02

Objective-C

(Uwaga: ta metoda nie gra przyjemnie w lokalizacjach różnic, ale jest nieco szybsza niż 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 Tak jest lepiej, naprawdę, ponieważ będzie dobrze grać z lokalizacjami i dziesiętnymi.

extension String {

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

Teraz możesz po prostu zrobić:

let someFloat = "42.42".numberValue
let someInt = "42".numberValue
 128
Author: Kevin R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-08 19:49:57

Dla łańcuchów zaczynających się od liczb całkowitych, np., @"123", @"456 ft", @"7.89", itd., użycie -[NSString integerValue].

Więc, @([@"12.8 lbs" integerValue]) jest jak robienie [NSNumber numberWithInteger:12].

 87
Author: ma11hew28,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-25 16:59:51

Możesz również to zrobić:

NSNumber *number = @([dictionary[@"id"] intValue]]);
Baw się dobrze!
 50
Author: MacMark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-05 13:13:59

Jeśli wiesz, że otrzymujesz liczby całkowite, możesz użyć:

NSString* val = @"12";
[NSNumber numberWithInt:[val intValue]];
 27
Author: Ad1905,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-10 00:35:29

Oto próbka pracy nsnumberformatter odczytu zlokalizowanego numeru NSString (xCode 3.2.4, osX 10.6), aby zaoszczędzić innym godziny, które właśnie spędziłem na bałaganie. Uwaga: chociaż może obsługiwać końcowe spacje( działa"8,765.4"), nie może obsługiwać wiodących białych spacji i nie może obsługiwać bezpańskich znaków tekstowych. (Złe ciągi wejściowe: "8" i " 8q "oraz" 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
 12
Author: miker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-11-01 20:05:53

Chciałem zamienić łańcuch na podwójny. Powyższa odpowiedź nie do końca mi odpowiadała. Ale tak było: Jak zrobić konwersje łańcuchów w Objective-C?

Wszystko co zrobiłem to:

double myDouble = [myString doubleValue];
 6
Author: Anthony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:32

Dzięki Wszystkim! Jestem połączony sprzężenie zwrotne i wreszcie udaje się przekonwertować z wejścia tekstowego (string) do liczby całkowitej. Poza tym może mi powiedzieć czy wejście jest 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];
 6
Author: DNA App Lab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-30 15:43:56

Myślę, że NSDecimalNumber to zrobi:

Przykład:

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

NSDecimalNumber jest podklasą NSNumber, więc dozwolone jest dyskretne odlewanie.

 4
Author: JeanNicolas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-20 08:57:22

A co ze standardem C atoi?

int num = atoi([scannedNumber cStringUsingEncoding:NSUTF8StringEncoding]);
Myślisz, że są jakieś zastrzeżenia?
 2
Author: martin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-27 12:55:50

Możesz po prostu użyć [string intValue] LUB [string floatValue] lub [string doubleValue] itp

Możesz również użyć NSNumberFormatter klasa:

 2
Author: user1479883,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-23 18:42:55

Możesz również zrobić jak ten kod 8.3.3 iOS 10.3 wsparcie

[NSNumber numberWithInt:[@"put your string here" intValue]]
 2
Author: Parv Bhasker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-07 06:33:49
NSDecimalNumber *myNumber = [NSDecimalNumber decimalNumberWithString:@"123.45"];
NSLog(@"My Number : %@",myNumber);
 1
Author: Sandip Patel - SM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-08 07:18:32

Pracował w Swift 3

NSDecimalNumber(string: "Your string") 
 0
Author: user431791,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-23 08:18:39

Wiem, że jest bardzo późno, ale poniższy kod działa dla mnie.

Wypróbuj ten kod

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

To może Ci pomóc. Dzięki
 0
Author: Ashu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-27 07:27:57

Spróbuj tego

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

Uwaga-użyłem longLongValue zgodnie z moimi wymaganiami. Możesz również użyć integerValue, longValue lub dowolnego innego formatu w zależności od wymagań.

 0
Author: Rizwan Ahmed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-09 08:10:51
extension String {

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

let someFloat = "12.34".numberValue
 -1
Author: Ankit garg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-12 18:55:02