4

I've written a simple swift program to show how much it costs to run electrical devices. The program works fine (all be it a little clunky - I'm new to swift!) but the result shows several figures after the decimal point so I've attempted to round it off to two decimal places. I'm not having much luck! My code is:

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") 

From what I've read here, roundTo(places: 2) is used but this resulted in the error

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

Any pointers would be greatly appreciated!

Thanks

sark
  • 71
  • 2
  • 6
  • 1
    The link provided by Leo Dabus does show my question to be a duplicate. For those who might fall upon this in the future, I was able to use `var cost: String = String(format:"%.2f", poundMonth)` This provided the desired result. Thanks. – sark Sep 30 '17 at 22:45

1 Answers1

6

Double indeed has no method roundTo(places:). That‘s a method you would first have to implement yourself. To do that, see this answer, for example.

Or, if you don’t want to create a separate method, you could directly do this (inspired by the aforementioned answer):

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

BUT: If you don‘t need the rounded value for any further calculations, but want to display it to the user, NumberFormatter is the way to go. For example, it also offers localization. See this answer.

Lennart Wisbar
  • 322
  • 1
  • 11