Objective-c将Long和float转换为String

Mar*_*mix 28 objective-c nsstring

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

一个是长号,另一个是浮点数.

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

我试试

NSString *myString = [NSString stringWithFormat: @"%f", floatValue]
Run Code Online (Sandbox Code Playgroud)

对于12345678.1234并获得"12345678.00000"作为输出

NSString *myString = [NSString stringWithFormat: @"%d", longValue]
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何正确使用stringWithFormat:

Cra*_*tis 62

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

字符串编程指南:格式化字符串对象

哪个使用此处指定的格式:

字符串编程指南:字符串格式说明符

对于你的浮动,你需要:

[NSString stringWithFormat:@"%1.6f", floatValue]
Run Code Online (Sandbox Code Playgroud)

而且你的长期:

[NSString stringWithFormat:@"%ld", longValue] // Use %lu for unsigned longs
Run Code Online (Sandbox Code Playgroud)

但老实说,有时候使用这NSNumber门课更容易:

[[NSNumber numberWithFloat:floatValue] stringValue];
[[NSNumber numberWithLong:longValue] stringValue];
Run Code Online (Sandbox Code Playgroud)

  • 这是个好问题.小数点右边的数字表示浮点值应该舍入的位数.对于float 1.123456,格式字符串%1.2f将返回1.12,格式字符串%1.4f将返回1.1234 (10认同)