将一个双精度数四舍五入

huangapple go评论65阅读模式
英文:

Rounding off a double

问题

@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(String(format: "%.2f", finalGrade))
        .foregroundColor(.blue)
}

}

.navigationTitle("Grade Calculator")

英文:
@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.

答案1

得分: 0

你可以在需要显示到特定小数位时使用文本格式指定符。我更喜欢这种方法,以便与变量本身一起进行更准确的计算,然后仅在 Text() 中用于显示时截断小数位。例如,要显示为 2 个小数位,使用以下格式指定符:

specifier: "%.2f"

英文:

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"

答案2

得分: 0

现代的方式是

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

这会将90.2554四舍五入为90.26。如果你想始终向下舍入,可以使用

Text(finalGrade.formatted(.number.rounded(rule: .down).precision(.fractionLength(2))))
英文:

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))))

huangapple
  • 本文由 发表于 2023年2月24日 04:41:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定