我编写了一个简单的 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")
Run Code Online (Sandbox Code Playgroud)
根据我在此处阅读的内容,roundTo(places: 2)已使用,但这导致错误
error: Power Costs.playground:6:12: error: value of type 'Double' has no member 'roundTo'
var cost = poundMonth.roundTo(places: 2)
Run Code Online (Sandbox Code Playgroud)
任何指针将不胜感激!
谢谢
小智 5
双确实没办法roundTo(places:)。这是您首先必须自己实现的方法。为此,例如,请参阅此答案。
或者,如果您不想创建单独的方法,则可以直接执行此操作(受上述答案的启发):
let cost = (poundMonth * 100).rounded() / 100
Run Code Online (Sandbox Code Playgroud)
但是:如果您不需要任何进一步计算的舍入值,但想将其显示给用户,则 NumberFormatter 是要走的路。例如,它还提供本地化。看到这个答案。
| 归档时间: |
|
| 查看次数: |
7935 次 |
| 最近记录: |