Full value in hours with Golang

Asked

Viewed 53 times

0

I’m trying to compare 2 dates that have only 1 minute difference between them and apply a price rule based on that time where;

Each minute must have the value of R$0.10

st := time.Date(2019, 9, 21, 10, 10, 10, 0, time.UTC)
en := time.Date(2019, 9, 21, 10, 11, 10, 0, time.UTC)
diff := en.Sub(st) // 1m0s

When comparing the dates that have 0 hours difference the value obtained is:

hours := (diff.Hours() * 60) * 0.10
// diff.Hours() é 0.016666666666666666 e não 0

minutes := diff.Minutes() * 0.10

Expected: 0.10

Obtained: 0.20

As the commentary suggests, the time is not absolute zero and so the calculation will not be correct if and convert to zero with int() the code will not compile as I will be trying to do an operation between int and float64.

How can I take the entire value of the difference between the hours?

1 answer

3


As in other languages, using math.Round:

Round Returns the Nearest integer, rounding half away from zero.

This way, it will truncate to the nearest integer value, in your case 0.016666666666666666 will be 0.

After importing the math, only do:

round := math.Round(diff.Hours())

Here is an example running on Go Playground

Browser other questions tagged

You are not signed in. Login or sign up in order to post.