Whole value in hours with Golang

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 should have the value of $ 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 of 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 comment suggests, the time is not absolute zero and so the calculation will not be correct, if it converts to zero with int() the code will not compile because I will be trying to do an operation between int and float64 .

How can I get the integer value of the time difference?

    
asked by anonymous 01.10.2018 / 01:52

1 answer

1

As in other languages, using math.Round :

  

Round returns the nearest integer, rounding half away from zero.

In this way, it will truncate to the nearest integer value, in which case 0.016666666666666666 will be 0 .

After importing math , just do:

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

Here's an example running on Go Playground

    
01.10.2018 / 03:08