Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 793
Vrushank Doshi Avatar asked Sep 28 '15 03:09

Vrushank Doshi


1 Answers

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.

like image 195
Bayta Darell Avatar answered Oct 02 '22 13:10

Bayta Darell