binavol329
binavol329

Reputation: 3

How to convert double to int and display it on Text in swiftUI?

I've created an Double variable and in the view it's displaying like "1.0" I just want to display it in "1" so how can I do conversion in text to display it.

Text("Here: \(Int(myViewModel.myModel.doubleValue.description))")
                        .font(.body)

When I add Int near I'm getting this error

error image

Upvotes: 0

Views: 2397

Answers (3)

NRitH
NRitH

Reputation: 13893

The Int() initializer that takes a string can return a nil value if the string can't be converted. You just need to give it a default to fall back on, like:

Text("Here: \(Int(myViewModel.myModel.doubleValue.description) ?? 0)")
                        .font(.body)

Upvotes: 1

Jignesh Mayani
Jignesh Mayani

Reputation: 7193

You can achieve all format like as below example

let doubleValue : Double = 5.33435

Text("\(String(format: "%.1f", doubleValue))") ---> 5.3
Text("\(String(format: "%.2f", doubleValue))") ---> 5.33
Text("\(String(format: "%.3f", doubleValue))") ---> 5.334

So, You can use String formating for this like as below

Text("Here: \(String(format: "%.0f", myViewModel.myModel.doubleValue))")
        .font(.body)

Here is output

enter image description here

Upvotes: 1

aheze
aheze

Reputation: 30318

Just wrap it in an Int.

     // here! ↓
Text("Here: \(Int(myViewModel.myModel.doubleValue.description))")
                        .font(.body)

Upvotes: 0

Related Questions