2017-09-30 179 views
0

我寫了一個簡單的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) 

任何指針將不勝感激!

感謝

+0

Leo Dabus提供的鏈接確實表明我的問題是重複的。對於那些未來可能會遇到的問題,我可以使用'var cost:String = String(format:「%。2f」,poundMonth)'這提供了期望的結果。謝謝。 – sark

回答

3

雙確實沒有方法roundTo(places:)。這是您首先必須實施的一種方法。 要做到這一點,請參閱this answer

或者,如果你不希望創建一個單獨的方法,你可以直接做到這一點(通過上述答案的啓發):

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

但是: 如果您不需要舍入值對於任何進一步的計算,但想要顯示給用戶,NumberFormatter是要走的路。例如,它也提供本地化。見this answer