cocoa - 将double转换为string

时间:2022-09-10 22:35:11

I have a double number and I would like to convert it to string.

我有一个双号,我想将其转换为字符串。

The number is, for example, something like

例如,这个数字就像是

24.043333332154465777...

but if I convert it to string using something like

但如果我使用类似的东西将其转换为字符串

NSString *myString = [NSString stringWithFormat:@"%f", myDouble];

The string is just

字符串就是

24.043333

how do I get a full string the corresponds to the whole double number? What other methods do I have to convert this?

如何获得与整个双号对应的完整字符串?我有什么其他方法来转换它?

5 个解决方案

#1


40  

Another option, since you asked for other ways in your comment to mipadi's answer:

另一种选择,因为你在评论mipadi的答案中要求其他方式:

Create an NSNumber using NSNumber *myDoubleNumber = [NSNumber numberWithDouble:myDouble];

使用NSNumber创建NSNumber * myDoubleNumber = [NSNumber numberWithDouble:myDouble];

Then call [myDoubleNumber stringValue];

然后调用[myDoubleNumber stringValue];

From the docs:

来自文档:

Returns the receiver’s value as a human-readable string, created by invoking descriptionWithLocale: where locale is nil.

将接收者的值作为人类可读的字符串返回,通过调用descriptionWithLocale创建:其中locale为nil。

#2


21  

[NSString stringWithFormat:@"%.20f", myDouble];

or

@(myDouble).stringValue;

#3


12  

You can pass a width format specifier to stringWithFormat.

您可以将宽度格式说明符传递给stringWithFormat。

NSString *myString = [NSString stringWithFormat:@"%.20f", myDouble];

will format myDouble with 20 decimal places.

将myDouble格式化为20位小数。

#4


2  

There's also NSNumberFormatter.

还有NSNumberFormatter。

#5


2  

[NSString stringWithFormat:@"%.0f", myDouble];

[NSString stringWithFormat:@“%。0f”,myDouble];

Use this for no decimal value

使用此选项无小数值

#1


40  

Another option, since you asked for other ways in your comment to mipadi's answer:

另一种选择,因为你在评论mipadi的答案中要求其他方式:

Create an NSNumber using NSNumber *myDoubleNumber = [NSNumber numberWithDouble:myDouble];

使用NSNumber创建NSNumber * myDoubleNumber = [NSNumber numberWithDouble:myDouble];

Then call [myDoubleNumber stringValue];

然后调用[myDoubleNumber stringValue];

From the docs:

来自文档:

Returns the receiver’s value as a human-readable string, created by invoking descriptionWithLocale: where locale is nil.

将接收者的值作为人类可读的字符串返回,通过调用descriptionWithLocale创建:其中locale为nil。

#2


21  

[NSString stringWithFormat:@"%.20f", myDouble];

or

@(myDouble).stringValue;

#3


12  

You can pass a width format specifier to stringWithFormat.

您可以将宽度格式说明符传递给stringWithFormat。

NSString *myString = [NSString stringWithFormat:@"%.20f", myDouble];

will format myDouble with 20 decimal places.

将myDouble格式化为20位小数。

#4


2  

There's also NSNumberFormatter.

还有NSNumberFormatter。

#5


2  

[NSString stringWithFormat:@"%.0f", myDouble];

[NSString stringWithFormat:@“%。0f”,myDouble];

Use this for no decimal value

使用此选项无小数值