Please write your question in detail here.
In Swift, we are creating an app that calculates the batting average of baseball.
Batting average = number of hits (numberOfHits)/number of batting (atBats)

I want to delete the first place "0" when displaying the result, but I don't know how to do it.
Enter "3" in atBatsText with the following code,
If i enter "1" in numberOfHitsText,
The calculation result is "0.333".
I want to display it as ".333".

Applicable source code

@IBOutlet weak var atBatsText: UITextField!

@IBOutlet weak var numberOfHitsText: UITextField!

@IBOutlet weak var battingAverageResult: UILabel!

@IBAction func calculate (_ sender: Any) {

let AtBats = Int (atBatsText.text!)
let numberOfHits = Int (numberOfHitsText.text!)
let result = Double (numberOfHits!)/Double (AtBats!)
let average = Double (result)

battingAverageResult.text = String (format: "% .3f", average)

I'm thinking that if I add something to "% .3f", the first place will disappear, but I don't know how.

I'm still a beginner and I'm wondering how to read the code. Can you tell me how to solve it?

  • Answer # 1

    How about multiplying by 1000 to int and ".% 03d"

    Is it different from C?
    Anyway, multiply by 1000, cast to int, and "% 03d" will come out with 3 digits, so just put a period in front of it! That's it.