英文:
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))))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论