String formatting of a Double [duplicate]

假如想象 提交于 2019-12-28 02:49:11

问题


I can't seem to find a way to format a Double limiting the precision to just a couple of positions after the decimal point when presenting that in a label. Maybe I'm missing something major, but I couldn't find anything in the official documentation.

Thanks in advance for the help!


回答1:


There's no way to do this using String interpolation.

You can find a good discussion about this on this Apple Dev Forum post.

You can use NSNumberFormatter or NSDateFormatter to format the output.

Alternatively, to use printf-like syntax, you can still use NSString:

var str = NSString(format: "Hello, world %.2f", 42.12312312313)



回答2:


Unsure if there is a pure Swift-way but you can always use NSStrings +stringWithFormat::

let str = NSString(format: "%.2f", 1.23)


来源:https://stackoverflow.com/questions/24047374/string-formatting-of-a-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!