Objective-c将Long和float转换为字符串

Objective-c将Long和float转换为字符串,objective-c,nsstring,Objective C,Nsstring,我需要在Objective-C中将两个数字转换成字符串 一个是长数字,另一个是浮点数 我在互联网上搜索了一个解决方案,每个人都使用stringWithFormat:,但我无法让它工作 我试着 NSString *myString = [NSString stringWithFormat: @"%f", floatValue] 对于12345678.1234,获取“12345678.00000”作为输出 及 有人能告诉我如何正确使用stringWithFormat吗?floatValue必须是双

我需要在Objective-C中将两个数字转换成字符串

一个是长数字,另一个是浮点数

我在互联网上搜索了一个解决方案,每个人都使用
stringWithFormat:
,但我无法让它工作

我试着

NSString *myString = [NSString stringWithFormat: @"%f", floatValue]
对于12345678.1234,获取“12345678.00000”作为输出


有人能告诉我如何正确使用stringWithFormat吗?

floatValue必须是双精度的。至少这可以正确编译,并在我的机器上执行预期的操作 浮点数只能存储大约8位十进制数字,您的数字12345678.1234需要更高的精度,因此浮点数中只存储大约8位最高有效数字

double floatValue = 12345678.1234;
NSString *myString = [NSString stringWithFormat: @"%f", floatValue];
导致

2011-11-04 11:40:26.295 Test basic command line[7886:130b] floatValue = 12345678.123400

本文讨论如何使用各种格式字符串将数字/对象转换为NSString实例:

其中使用此处指定的格式:

对于您的浮动,您需要:

[NSString stringWithFormat:@"%1.6f", floatValue]
为了你的长久:

[NSString stringWithFormat:@"%ld", longValue] // Use %lu for unsigned longs
但老实说,有时只使用
NSNumber
类更容易:

[[NSNumber numberWithFloat:floatValue] stringValue];
[[NSNumber numberWithLong:longValue] stringValue];

您应该使用NSNumberFormatter例如:

    NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init];
    [nFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *num = [nFormatter numberFromString:@"12345678.1234"];
    [nFormatter release];

由于我无法评论克雷格先生的回答,我将把它放在这里。使用%1.6f不能单独工作。如果浮点值是双精度的话,它可以正常工作。你能更具体一点吗?格式字符串%1.6f在浮点值上运行良好;NSString*myString=[NSString stringWithFormat:@“%1.6f”,floatValue]输出2011-11-04 12:25:43.133在我的机器上测试基本命令行[15718:707]floatValue=12345678.000000。在我的程序上也会发生同样的情况。我理解float和double之间的区别。实际上,这是问题的症结所在。浮点数不足以容纳12位小数,因为一个浮点数有6位指数和23位阵营(24位精度)。但24位可以存储大约7个十进制数(准确地说是7.229),这是数字的第一部分。因此,要存储12345678.1234,必须使用双精度。这在您提供的wikepedia页面上有很好的解释。我确实认为我的解决方案在xcode中仍然有效。这是一个好问题。小数点右边的数字表示浮点值应四舍五入的位数。对于浮点1.123456,格式字符串%1.2f将返回1.12,格式字符串%1.4f将返回1.1234
    NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init];
    [nFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *num = [nFormatter numberFromString:@"12345678.1234"];
    [nFormatter release];