Limit Number of Text Characters within Simple Text(“”) View

Hello CodeCrew Community,

I am having trouble setting a character limit for a dynamic piece of text; not a TextField, just the simple Text(“”) view model in Swift that draws a piece of data from an API. From doing a lot of research, I have found many ways to limit the number of characters within a TextField, but nothing that straightforwardly explains how to accomplish this with a Text(“”) view. It seems like a single modifier added to the Text element would be able to accomplish this, but I can’t seem to find one. I did try using the round() modifier, but if I do that, I lose the decimal placeholder.

My objective, in context, is to get rid of trailing zeros from rating data from the API I am using without losing the first decimal place: for example, 4.5 instead of 4.5000000 and 5.0 instead of 5.0000000. Here is the code:

HStack {
                        Text("\(business?.rating ?? 0)")
                            .padding(.leading)
                    }.padding(.bottom, 16)

Note: The number rating is to the right of the stars rating.

Thanks! Let me know if there’s any more info I should include.

-Michael :wink:

Hi Michael,

The solution is pretty simple (once you know how) and that is to use a string format. You do that like this:

let angle = 45.6789
let formattedString = String(format: "Angle: %.2f", angle)

Using that in a

Text(formattedString)

or

Text(String(format: "Angle: %.2f", angle))

The output on the screen is
Angle: 45.68

So in your case you could do it this way:

Text(String(format: "%.2f", business?.rating ?? 0))

Great! This works perfectly. Thanks for your help.

  • Michael
1 Like