UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Restrict the Items of Float in Text

Forums > SwiftUI

How can I restrict the item of a float value that is displayed in the Text() to 2 characters after the dot?

struct ContentView: View {
    let timer = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect()
    @State private var isButtonTapped: Bool = false
    @State private var currentTime: Float = 0

    var body: some View {
        VStack {
            Spacer()

            Text("\(currentTime)")
                .bold()
                .font(.custom("timeFont", size: 80))
                .lineLimit(1)
                .onReceive(timer) { _ in
                    if isButtonTapped == true {
                        currentTime += 0.01
                    }
                }

            Spacer()

            Button() {
                isButtonTapped.toggle()
            } label: {
                ZStack {
                    Rectangle()
                        .frame(width: 250, height: 150)
                        .foregroundColor(isButtonTapped ? .red : .blue)
                        .cornerRadius(20)

                    Label(isButtonTapped ? "Pause" : "Play", systemImage: isButtonTapped ? "pause.circle" : "play.circle")
                        .foregroundColor(.primary)
                        .font(.title)
                }
            }
        }.padding(50)
    }
}

3      

You can use a string format specifier, like so:

Text("\(currentTime, specifier: "%.2f")")

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.