-2
@State var value1 = 25.8711
@State var value2 = 30.6234
@State var value3 = 90.2534
@State var value4 = 87.3232
@State var value5 = 87.2334



var body: some View
{
    let finalGrade = (value1 + value2 + value3 + value4 + value5) / 5
   
    Section(header: Text("Average Grade")){
                    Text("\(finalGrade)")
                    
                        .foregroundColor(.blue)
                }
                
                
            }
            
            
            .navigationTitle("Grade Calculator")
}

In this block of code how would I get so that finalGrade variable is rounded off into two decimals, and outputs ie: 92.80 versus 92.801232 in the Text() box. The variables 'value' obviously do not calculate to that number but that is just an example.

HangarRash
  • 7,314
  • 5
  • 5
  • 32
msalaz03
  • 5
  • 2
  • Does this answer your question? https://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift – jnpdx Feb 23 '23 at 20:49

2 Answers2

0

You can use a text specifier when needing to display to a certain decimal place. I prefer this for more accurate calculations with the variables themselves and then it cuts off the decimals only for displaying within Text(). For instance, to show as 2 decimals use

specifier: "%.2f"

0

The modern way is

Text(finalGrade.formatted(.number.precision(.fractionLength(2))))

which rounds up 90.2554 to 90.26. If you want always to round down use

Text(finalGrade.formatted(.number.rounded(rule: .down).precision(.fractionLength(2))))
vadian
  • 274,689
  • 30
  • 353
  • 361