Reputation: 3
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
Upvotes: 0
Views: 2397
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
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
Upvotes: 1
Reputation: 30318
Just wrap it in an Int
.
// here! ↓
Text("Here: \(Int(myViewModel.myModel.doubleValue.description))")
.font(.body)
Upvotes: 0