How to perform division in Go

Vrushank Doshi picture Vrushank Doshi · Sep 28, 2015 · Viewed 67.5k times · Source

I am trying to perform a simple division in Go.

fmt.Println(3/10)

This prints 0 instead of 0.3. This is kind of weird. Could someone please share what is the reason behind this? i want to perform different arithmetic operations in Go.

Thanks

Answer

Cerise Limón picture Cerise Limón · Sep 28, 2015

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.