Double 的字符串格式 [英] String formatting of a Double

查看:29
本文介绍了Double 的字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎找不到一种方法来格式化 Double 在标签中显示时将精度限制在小数点后的几个位置.也许我遗漏了一些重要的东西,但我在官方文档中找不到任何东西.

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.

预先感谢您的帮助!

推荐答案

使用 String 插值无法做到这一点.

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

您可以在这篇 Apple Dev Forum 帖子上找到关于此的很好的讨论.

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

您可以使用 NSNumberFormatterNSDateFormatter 来格式化输出.

You can use NSNumberFormatter or NSDateFormatter to format the output.

或者,要使用类似 printf 的语法,您仍然可以使用 NSString:

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

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

这篇关于Double 的字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆