Swift 双到字符串 [英] Swift double to string

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

问题描述

在我更新 xCode 6 之前,我将 double 转换为字符串没有问题,但现在它给了我一个错误

Before I updated xCode 6, I had no problems casting a double to a string but now it gives me an error

var a: Double = 1.5
var b: String = String(a)

它给了我错误信息double is not convertible to string".还有其他方法吗?

It gives me the error message "double is not convertible to string". Is there any other way to do it?

推荐答案

它不是强制转换,而是根据具有格式的值创建字符串.

It is not casting, it is creating a string from a value with a format.

let a: Double = 1.5
let b: String = String(format: "%f", a)

print("b: (b)") // b: 1.500000

使用不同的格式:

let c: String = String(format: "%.1f", a)

print("c: (c)") // c: 1.5

如果不需要格式化,您也可以省略 format 属性.

You can also omit the format property if no formatting is needed.

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

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