How to perform division in Go

MathGoFloating PointInteger Division

Math Problem Overview


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

Math Solutions


Solution 1 - Math

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.

Solution 2 - Math

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVrushank DoshiView Question on Stackoverflow
Solution 1 - MathBayta DarellView Answer on Stackoverflow
Solution 2 - MathrobstarbuckView Answer on Stackoverflow