gohugoio/hugo · error

can't divide the value by 0

Error message

can't divide the value by 0

What it means

In the division (/) case, if the divisor is zero for int, float, or uint, Hugo refuses rather than producing a divide-by-zero panic or NaN. The check is exact-zero (bf != 0 / bu != 0 / bi != 0).

Solutions

  1. Guard the divisor with a non-zero check (if gt $denom 0) before dividing.
  2. Provide a sensible non-zero default for divisor params.
  3. Validate collection lengths before computing ratios.

Example fix

// before
{{ div $sum $count }}
// after
{{ if gt $count 0 }}{{ div $sum $count }}{{ else }}0{{ end }}
Defensive patterns

Strategy: validation

Validate before calling

// Guard divisor before dividing
switch dv := reflect.ValueOf(b); dv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
    if dv.Int() == 0 { return 0, errors.New("divisor is zero") }
case reflect.Float32, reflect.Float64:
    if dv.Float() == 0 { return 0, errors.New("divisor is zero") }
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
    if dv.Uint() == 0 { return 0, errors.New("divisor is zero") }
}
math.DoArithmetic(a, b, '/')

Type guard

func isNonZeroNumber(v any) bool {
    dv := reflect.ValueOf(v)
    switch dv.Kind() {
    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
        return dv.Int() != 0
    case reflect.Float32, reflect.Float64:
        return dv.Float() != 0
    case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
        return dv.Uint() != 0
    }
    return false
}

Prevention

When it happens

Trigger: {{ div $total 0 }}, or a divisor expression that evaluates to 0 such as the length of an empty list or a zeroed front-matter value.

Common situations: Computing averages or ratios where the denominator is an empty collection's count; pagination math with 0 items-per-page; missing divisor param defaulting to 0.

Related errors


AI-assisted analysis of gohugoio/hugo@52c9bd7908 (2026-08-09). Data as JSON: /api/errors/c2d46987f9afe765. Report an issue: GitHub.

Appendix: source

Thrown at common/math/math.go:129

			return af - bf, nil
		}
		return au - bu, nil
	case '*':
		if isInt {
			return ai * bi, nil
		} else if isFloat {
			return af * bf, nil
		}
		return au * bu, nil
	case '/':
		if isInt && bi != 0 {
			return ai / bi, nil
		} else if isFloat && bf != 0 {
			return af / bf, nil
		} else if isUint && bu != 0 {
			return au / bu, nil
		}
		return nil, errors.New("can't divide the value by 0")
	default:
		return nil, errors.New("there is no such an operation")
	}
}

View on GitHub (pinned to 52c9bd7908)