How to get a diff of integers

I have the feeling I am missing something, but maybe this is something missing in Hugo itself:

I am trying to get the difference between two integers. The problem is, the I don’t know which of the integers is the larger one.

Sample:

{{ $int1 := 1234 }}
{{ $int2 := 2345 }}
{{ $test1 := sub $int1 $int2 }} <-- result -1111
{{ $test2 := sub $int2 $int1 }} <-- result 1111

$int1 and int2 might be anything. What will be the proper way to assert that the difference between $int1 and $int2 is 1111 independently of their order/position?

Is there an easy way (a single function) or do I have to compare $int1 and $int2 so I can sort them before I am checking their difference?

Go provides the function Abs for that. I don’t know if it’s available in Hugo, though (the documentation doesn’t seem to mention it. But neither does one find sub nor mul unless one searches for Math). So, something like this should do the trick:

$diff := sub $a $b
if lt $diff 0
  $diff = mul $diff -1
end
2 Likes

We don’t have a math.Abs template function, and we should.

You can do this:

{{ $n := -3 }}
{{ math.Pow $n 2 | math.Sqrt }} --> 3 (float)
2 Likes

Seems a bit too much if a simple multiplication with -1 does the same thing, without converting to float (hopefully).

I was trying to tersely match the functionality of math.Abs, which returns a float.

I can work with that. Great solution.

1 Like

https://github.com/gohugoio/hugo/issues/10941

1 Like

Must be a few ways, probably doesn’t make any difference unless you have loads of the calculations to do but it might be cheaper if either of these work:

Either
Two subtractions and a comparison or
Two comparisons and a subtraction

{{ math.Max (sub $a $b) (sub $b $a) }}

{{ sub (math.Max $a $b) (math.Min $a $b) }}

Be interested in a benchmark, I think I’ve used a math.Pow somewhere for a similar reason.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.