Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 Xcode: How to display battery levels as an integer?

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!

like image 616
Matt Avatar asked Oct 26 '25 16:10

Matt


1 Answers

Try this instead:

func someFunction() {
    self.infoLabel.text = String(format: "%.0f%%", batteryLevel * 100)
}

For future reference, all string format specifiers are listed here.

like image 108
Paulo Mattos Avatar answered Oct 29 '25 07:10

Paulo Mattos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!