'How to perform division in Go
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
Solution 1:[1]
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))
Solution 2:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
