How to perform division in Go
Solution 1:
The expression 3 / 10
is an untyped constant expression. The specification says this about constant expressions
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).
One of the operands must be a floating-point constant for the result to 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
It's also possible to use typed constants. The following expressions evaluate to the float64
constant 0.3
:
float64(3) / float64(10)
float64(3) / 10
3 / float64(10)
Printing any of the above expressions will print 0.3
. For example, fmt.Println(3.0 / 10)
prints 0.3
.
Solution 2:
As mentioned by @Cerise and per the spec
Arithmetic operators apply to numeric values and yield a result of the same type as the first operand.
In this case only the first operand needs to be a floating point.
fmt.Println(3.0/10)
fmt.Println(float64(3)/10)
// 0.3 0.3
Example