Search code examples
swiftdoubledecimal-point

Reducing(Adjusting) Double/Float variable decimal points in swift


I'm trying to reduce the decimal points of this simple function which return the probability of something, but I learned that I need to convert the Double to String then reduce the decimals and return the string value in the result view.

Is there any way to force the Double variable(or other simpler way) to show only 2 decimal points in the result with swift 5.1 ?

    @State var pairCount = 0
    @State var rollCount = 0
    @State var pairChance : Double = 0


     Text("\(pairChance)    %")

     Button(action: {            
                      self.pairChance = Double(self.pairCount) / Double(self.rollCount) * 100.0
                      })

Solution

  • SwiftUI’s text views have an optional specifier parameter that lets us customize the way data is presented inside the label.

    @State var pairCount = 2
    @State var rollCount = 3
    @State var pairChance : Double = 0
    var body: some View {
        VStack {
            Text("\(pairChance, specifier: "%.2f")%")
            Button(action: {
                 self.pairChance = Double(self.pairCount) / Double(self.rollCount) * 100.0
            }) {
                Text("Calculate")
            }
        }
    }