如何在Objective-C中进行字符串转换?

时间:2022-05-05 19:20:47

I want to convert a string into a double and after doing some math on it, convert it back to a string.

我想把一个字符串转换成double,然后在它上面做一些数学运算后,把它转换成一个字符串。

How do I do this in Objective-C?

在Objective-C中怎么做呢?

Is there a way to round a double to the nearest integer too?

有没有一种方法可以将一个双精度数四舍五入到最近的整数?

12 个解决方案

#1


222  

You can convert an NSString into a double with

你可以将NSString转换成double。

double myDouble = [myString doubleValue];

Rounding to the nearest int can then be done as

四舍五入到最近的整数可以这样做

int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))

I'm honestly not sure if there's a more streamlined way to convert back into a string than

老实说,我不确定是否有一种更有效的方法可以将它转换成字符串

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

#2


69  

To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter configured for the locale from which you're reading the string.

要真正正确地从字符串转换为数字,您需要使用为您正在从中读取字符串的语言环境配置的NSNumberFormatter实例。

Different locales will format numbers differently. For example, in some parts of the world, COMMA is used as a decimal separator while in others it is PERIOD — and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.

不同的地区会有不同的数字格式。例如,在世界的某些地方,逗号被用作十进制分隔符,而在另一些地方,逗号是句号,而成千上万的分隔符(使用时)是颠倒的。除非它是一个空格。或者根本不在场。

It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter for the way your input is formatted and use -[NSFormatter numberFromString:] to get an NSNumber from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:] instead.

这取决于输入的来源。最安全的做法是配置一个NSNumberFormatter,用于格式化输入并使用-[NSFormatter numberFromString:]从其获取NSNumber。如果希望处理转换错误,可以使用-[NSFormatter getObjectValue:forString:range:error:]。

#3


32  

Adding to olliej's answer, you can convert from an int back to a string with NSNumber's stringValue:

添加到olliej的答案中,您可以将int类型转换回带有NSNumber的stringValue的字符串:

[[NSNumber numberWithInt:myInt] stringValue]

stringValue on an NSNumber invokes descriptionWithLocale:nil, giving you a localized string representation of value. I'm not sure if [NSString stringWithFormat:@"%d",myInt] will give you a properly localized reprsentation of myInt.

NSNumber上的stringValue调用descriptionWithLocale:nil,为您提供值的本地化字符串表示。我不确定[NSString stringWithFormat:@"%d",myInt]会给您一个正确的myInt的本地化的回缩。

#4


7  

olliej's rounding method is wrong for negative numbers

对于负数,olliej的舍入法是错误的

  • 2.4 rounded is 2 (olliej's method gets this right)
  • 2.4四舍五入是2 (olliej方法正确)
  • −2.4 rounded is −2 (olliej's method returns -1)
  • −2.4圆−2(olliej方法返回1)

Here's an alternative

这是另一个

  int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))

You could of course use a rounding function from math.h

当然,你可以使用math。h的舍入函数。

#5


6  

Here's a working sample of NSNumberFormatter reading localized number String (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 such as "8,765.4 ", this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)

这里有一个NSNumberFormatter的工作示例,该示例读取本地化的number字符串(xCode 3.2.4, osX 10.6),以节省我刚刚浪费的时间。注意:虽然它可以处理诸如“8,765.4”这样的结尾空白,但它不能处理前面的空白,而且不能处理零散的文本字符。(糟糕的输入字符串:“8”和“8q”和“8q”)。

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

#6


3  

// Converting String in to Double

double doubleValue = [yourString doubleValue];

// Converting Double in to String
NSString *yourString = [NSString stringWithFormat:@"%.20f", doubleValue];
// .20f takes the value up to 20 position after decimal

// Converting double to int

int intValue = (int) doubleValue;
or
int intValue = [yourString intValue];

#7


2  

For rounding, you should probably use the C functions defined in math.h.

对于四舍五入,您可能应该使用math.h中定义的C函数。

int roundedX = round(x);

Hold down Option and double click on round in Xcode and it will show you the man page with various functions for rounding different types.

按住Option并双击Xcode中的round,它将显示带有各种函数的man页面,用于对不同类型进行舍入。

#8


2  

For conversion from a number to a string, how about using the new literals syntax (XCode >= 4.4), its a little more compact.

对于从一个数字转换到一个字符串,如何使用新的文本语法(XCode >= 4.4),它更紧凑一些。

int myInt = (int)round( [@"1.6" floatValue] );

NSString* myString = [@(myInt) description];

(Boxes it up as a NSNumber and converts to a string using the NSObjects' description method)

(将它作为一个NSNumber框起来,并使用NSObjects的描述方法将其转换为字符串)

#9


1  

This is the easiest way I know of:

这是我所知道的最简单的方法:

float myFloat = 5.3;
NSInteger myInt = (NSInteger)myFloat;

#10


1  

from this example here, you can see the the conversions both ways:

从这个例子中,你可以看到两种方式的转换:

NSString *str=@"5678901234567890";

long long verylong;
NSRange range;
range.length = 15;
range.location = 0;

[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];

NSLog(@"long long value %lld",verylong);

#11


1  

convert text entered in textfield to integer

将textfield中输入的文本转换为integer

double mydouble=[_myTextfield.text doubleValue];

rounding to the nearest double

四舍五入到最近的双精度浮点数

mydouble=(round(mydouble));

rounding to the nearest int(considering only positive values)

四舍五入到最近的整数(只考虑正值)

int myint=(int)(mydouble);

converting from double to string

从双字符串转换为字符串

myLabel.text=[NSString stringWithFormat:@"%f",mydouble];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];

converting from int to string

从int转换为string

myLabel.text=[NSString stringWithFormat:@"%d",myint];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];

#12


1  

I ended up using this handy macro:

最后我使用了这个简单的宏:

#define STRING(value)               [@(value) stringValue]

#1


222  

You can convert an NSString into a double with

你可以将NSString转换成double。

double myDouble = [myString doubleValue];

Rounding to the nearest int can then be done as

四舍五入到最近的整数可以这样做

int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))

I'm honestly not sure if there's a more streamlined way to convert back into a string than

老实说,我不确定是否有一种更有效的方法可以将它转换成字符串

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

#2


69  

To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter configured for the locale from which you're reading the string.

要真正正确地从字符串转换为数字,您需要使用为您正在从中读取字符串的语言环境配置的NSNumberFormatter实例。

Different locales will format numbers differently. For example, in some parts of the world, COMMA is used as a decimal separator while in others it is PERIOD — and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.

不同的地区会有不同的数字格式。例如,在世界的某些地方,逗号被用作十进制分隔符,而在另一些地方,逗号是句号,而成千上万的分隔符(使用时)是颠倒的。除非它是一个空格。或者根本不在场。

It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter for the way your input is formatted and use -[NSFormatter numberFromString:] to get an NSNumber from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:] instead.

这取决于输入的来源。最安全的做法是配置一个NSNumberFormatter,用于格式化输入并使用-[NSFormatter numberFromString:]从其获取NSNumber。如果希望处理转换错误,可以使用-[NSFormatter getObjectValue:forString:range:error:]。

#3


32  

Adding to olliej's answer, you can convert from an int back to a string with NSNumber's stringValue:

添加到olliej的答案中,您可以将int类型转换回带有NSNumber的stringValue的字符串:

[[NSNumber numberWithInt:myInt] stringValue]

stringValue on an NSNumber invokes descriptionWithLocale:nil, giving you a localized string representation of value. I'm not sure if [NSString stringWithFormat:@"%d",myInt] will give you a properly localized reprsentation of myInt.

NSNumber上的stringValue调用descriptionWithLocale:nil,为您提供值的本地化字符串表示。我不确定[NSString stringWithFormat:@"%d",myInt]会给您一个正确的myInt的本地化的回缩。

#4


7  

olliej's rounding method is wrong for negative numbers

对于负数,olliej的舍入法是错误的

  • 2.4 rounded is 2 (olliej's method gets this right)
  • 2.4四舍五入是2 (olliej方法正确)
  • −2.4 rounded is −2 (olliej's method returns -1)
  • −2.4圆−2(olliej方法返回1)

Here's an alternative

这是另一个

  int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))

You could of course use a rounding function from math.h

当然,你可以使用math。h的舍入函数。

#5


6  

Here's a working sample of NSNumberFormatter reading localized number String (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 such as "8,765.4 ", this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)

这里有一个NSNumberFormatter的工作示例,该示例读取本地化的number字符串(xCode 3.2.4, osX 10.6),以节省我刚刚浪费的时间。注意:虽然它可以处理诸如“8,765.4”这样的结尾空白,但它不能处理前面的空白,而且不能处理零散的文本字符。(糟糕的输入字符串:“8”和“8q”和“8q”)。

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

#6


3  

// Converting String in to Double

double doubleValue = [yourString doubleValue];

// Converting Double in to String
NSString *yourString = [NSString stringWithFormat:@"%.20f", doubleValue];
// .20f takes the value up to 20 position after decimal

// Converting double to int

int intValue = (int) doubleValue;
or
int intValue = [yourString intValue];

#7


2  

For rounding, you should probably use the C functions defined in math.h.

对于四舍五入,您可能应该使用math.h中定义的C函数。

int roundedX = round(x);

Hold down Option and double click on round in Xcode and it will show you the man page with various functions for rounding different types.

按住Option并双击Xcode中的round,它将显示带有各种函数的man页面,用于对不同类型进行舍入。

#8


2  

For conversion from a number to a string, how about using the new literals syntax (XCode >= 4.4), its a little more compact.

对于从一个数字转换到一个字符串,如何使用新的文本语法(XCode >= 4.4),它更紧凑一些。

int myInt = (int)round( [@"1.6" floatValue] );

NSString* myString = [@(myInt) description];

(Boxes it up as a NSNumber and converts to a string using the NSObjects' description method)

(将它作为一个NSNumber框起来,并使用NSObjects的描述方法将其转换为字符串)

#9


1  

This is the easiest way I know of:

这是我所知道的最简单的方法:

float myFloat = 5.3;
NSInteger myInt = (NSInteger)myFloat;

#10


1  

from this example here, you can see the the conversions both ways:

从这个例子中,你可以看到两种方式的转换:

NSString *str=@"5678901234567890";

long long verylong;
NSRange range;
range.length = 15;
range.location = 0;

[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];

NSLog(@"long long value %lld",verylong);

#11


1  

convert text entered in textfield to integer

将textfield中输入的文本转换为integer

double mydouble=[_myTextfield.text doubleValue];

rounding to the nearest double

四舍五入到最近的双精度浮点数

mydouble=(round(mydouble));

rounding to the nearest int(considering only positive values)

四舍五入到最近的整数(只考虑正值)

int myint=(int)(mydouble);

converting from double to string

从双字符串转换为字符串

myLabel.text=[NSString stringWithFormat:@"%f",mydouble];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];

converting from int to string

从int转换为string

myLabel.text=[NSString stringWithFormat:@"%d",myint];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];

#12


1  

I ended up using this handy macro:

最后我使用了这个简单的宏:

#define STRING(value)               [@(value) stringValue]