How to perform division in Go

The operands of the binary operation 3 / 10 are untyped constants. The specification says this about binary operations with untyped constants

if the operands of a binary operation are different kinds of untyped constants, the operation and, for non-boolean operations, the result use the kind that appears later in this list: integer, rune, floating-point, complex.

Because 3 and 10 are untyped integer constants, the value of the expression is an untyped integer (0 in this case).

To get a floating-point constant result, one of the operands must be a floating-point constant. The following expressions evaluate to the untyped floating-point constant 0.3:

3.0 / 10.0
3.0 / 10
3 / 10.0

When the division operation has an untyped constant operand and a typed operand, the typed operand determines the type of the expression. Ensure that the typed operand is a float64 to get a float64 result.

The expressions below convert int variables to a float64 to get the float64 result 0.3:

var i3 = 3
var i10 = 10
fmt.Println(float64(i3) / 10)
fmt.Println(3 / float64(i10))

Run a demonstration playground.

Leave a Comment