I am making an app to read battery percentage using Swift! Right now my out is something like this: 61.0% or 24.0% or 89.0% What I'm trying to fix is getting rid of the .0 so it's an Int. This is my code so far:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var infoLabel: UILabel!
var batteryLevel: Float {
return UIDevice.current.batteryLevel
}
var timer = Timer()
func scheduledTimerWithTimeInterval(){
timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(self.someFunction), userInfo: nil, repeats: true)
}
func someFunction() {
self.infoLabel.text = "\(batteryLevel * 100)%"
}
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.current.isBatteryMonitoringEnabled = true
someFunction()
scheduledTimerWithTimeInterval()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I have tried something like this:
var realBatteryLevel = Int(batteryLevel)
However, I get this error
I have tried other method but none with any luck. Please, any solutions would be awesome! Thanks in advance!
EDIT
I was considering making the float batteryLevel
into a String and then replacing ".0" with "" and I have seen this somewhere, however, I'm not sure how!
Try this instead:
func someFunction() {
self.infoLabel.text = String(format: "%.0f%%", batteryLevel * 100)
}
For future reference, all string format specifiers are listed here.