我认为标题已经说明了一切,但让我再深入一点。
当用户使用我的应用程序时,我每 5 分钟将小数小时存储在数据库中。我在显示某些 5 分钟 block 的正确时间时遇到了一些麻烦,因为它显示了 4 分 60 秒。每 3 个 5 分钟 block 显示一次。
像这样
4:60
10:00
15:00
19:60
有些甚至有 n:59 而不是 n:00
部分代码为:
let hours = Int(floor(decimalHour))
let mins = Int(floor(decimalHour * 60) % 60)
let secs = Int(floor(decimalHour * 3600) % 60)
有什么我可能做错的建议吗?
最佳答案
二进制 float 不能表示所有数 确切地说,因此您的代码容易出现舍入错误。 示例( swift 2):
let decimalHour = 1.0 + 5.0/60.0
print(decimalHour.debugDescription) // 1.0833333333333333
print(floor(decimalHour * 3600)) // 3899.0
let hours = Int(floor(decimalHour))
let mins = Int(floor(decimalHour * 60) % 60)
let secs = Int(floor(decimalHour * 3600) % 60)
print(hours, mins, secs) // 1 5 59
decimalHour
中实际存储的数字略小于1 + 5/60
,因此秒计算错误。
(另请注意,您不能将 %
与 float 一起使用
在 Swift 3 中,比较 What does "% is unavailable: Use truncatingRemainder instead" mean? .)
如评论中所述,更好的方法是 将持续时间存储为整数(秒数)。
如果这不可能,舍入 float 为 a 秒数,然后用纯整数继续 算术。示例(适用于 Swift 2+3):
let decimalHour = 1.0 + 5.0/60.0
let totalSeconds = lrint(decimalHour * 3600) // round to seconds
let hours = totalSeconds / 3600
let mins = (totalSeconds % 3600) / 60
let secs = totalSeconds % 60
print(hours, mins, secs) // 1 5 0
关于swift - 十进制小时显示 4 分 60 秒而不是 5 分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41207067/