舍入一个双倍到两个小数点

时间:2017-09-30 21:50:32

标签: swift

我写了一个简单的快速程序,以显示运行电子设备的成本。该程序工作正常(所有这一切都有点笨重 - 我是swift的新手!)但结果显示小数点后的几个数字,所以我试图将它四舍五入到小数点后两位。我运气不好!我的代码是:

var pricePerkWh: Double = 13.426
var watts: Double = 5.0
var hours: Double = 730.0
var KW: Double = watts/1000
var kWh: Double = KW*hours
var penceMonth: Double = kWh*pricePerkWh
var poundMonth:Double = penceMonth/100
var cost = poundMonth.roundTo(places: 2)


print ("It will cost £\(cost) per month") 

根据我的阅读here,使用roundTo(places: 2),但这会导致错误

error: Power Costs.playground:6:12: error: value of type 'Double' has no member 'roundTo'
var cost = poundMonth.roundTo(places: 2)

任何指针都将非常感谢!

由于

1 个答案:

答案 0 :(得分:4)

Double确实没有方法roundTo(places:)。这是你首先要自己实现的方法。 为此,请参阅this answer,例如。

或者,如果您不想创建单独的方法,可以直接执行此操作(受上述答案的启发):

let cost = (poundMonth * 100).rounded() / 100

BUT: 如果您不需要舍入值进行任何进一步的计算,但想要将其显示给用户,则可以使用NumberFormatter。例如,它还提供本地化。请参阅this answer