func formatDuration has a bug will to output wrong result
eager7 opened this issue · comments
function formatDuration use string to create ass timeline,but if the precision carry, then will output a wrong timeline.
ex:
00:48:35,039 --> 00:48:35,999
the timestamp 00:48:35,999
convert to ass timeline,will output:
00:48:35.04,00:48:35.00
the end time is before than bengin time.
becuse fmt.Sprintf("%.2f", 0.999)
is equal 1.00
,when use slice to get result,will lose precision.
t.Log(fmt.Sprintf("%."+strconv.Itoa(2)+"f", 0.999)[2:])
will output 0.
this is my temporary solution:
import "github.com/shopspring/decimal"
// formatDuration formats a duration
func formatDuration(i time.Duration, millisecondSep string, numberOfMillisecondDigits int) (s string) {
// Parse hours
var hours = int(i / time.Hour)
var n = i % time.Hour
if hours < 10 {
s += "0"
}
s += strconv.Itoa(hours) + ":"
// Parse minutes
var minutes = int(n / time.Minute)
n = i % time.Minute
if minutes < 10 {
s += "0"
}
s += strconv.Itoa(minutes) + ":"
// Parse seconds
var seconds = int(n / time.Second)
n = i % time.Second
if seconds < 10 {
s += "0"
}
s += strconv.Itoa(seconds) + millisecondSep
// Parse milliseconds
var milliseconds = float64(n/time.Millisecond) / float64(1000)
// PCT 解决精度丢失问题
decimalMs := decimal.NewFromFloat(milliseconds)
round := decimalMs.RoundFloor(int32(numberOfMillisecondDigits)).InexactFloat64()
s += fmt.Sprintf("%."+strconv.Itoa(numberOfMillisecondDigits)+"f", round)[2:]
// s += fmt.Sprintf("%."+strconv.Itoa(numberOfMillisecondDigits)+"f", milliseconds)[2:]
return
}
I've pushed a fix on master based on your provided test data, could you confirm your problem is now resolved?
Let me know whether you need a tag 👍
I've pushed a fix on master based on your provided test data, could you confirm your problem is now resolved?
Let me know whether you need a tag 👍
There's nothing wrong with my test,tks
Closing this issue then 👍