Float variable is casted to float64

77 views
Skip to first unread message

Archos

unread,
Oct 17, 2011, 6:26:33 AM10/17/11
to golang-nuts
Why when is assigned a float number to a variable (a := 1.5), it is
casted auto. to float64 instead of to be casted to float32 (since it's
a small value)?


===
package main

import (
"fmt"
)

func main() {
a := 1.5
fmt.Printf("%T : %v\n", a,a)
}
===

Archos

unread,
Oct 17, 2011, 6:33:08 AM10/17/11
to golang-nuts
float64 : 1.5

Jan Mercl

unread,
Oct 17, 2011, 6:43:50 AM10/17/11
to golan...@googlegroups.com
It's all in the specs.


If the type is present, each variable is given that type. Otherwise, the types are deduced from the assignment of the expression list.

If the type is absent and the corresponding expression evaluates to an untyped constant, the type of the declared variable is boolintfloat64, or string respectively, depending on whether the value is a boolean, integer, floating-point, or string constant:

var b = true    // t has type bool
var i = 0       // i has type int
var f = 3.0     // f has type float64 
var s = "OMDB" // s has type string


short variable declaration uses the syntax:

ShortVarDecl = IdentifierList ":=" ExpressionList .

It is a shorthand for a regular variable declaration with initializer expressions but no types:

"var" IdentifierList = ExpressionList .

 

Peter Bourgon

unread,
Oct 17, 2011, 6:48:09 AM10/17/11
to golan...@googlegroups.com

unread,
Oct 17, 2011, 7:26:33 AM10/17/11
to golang-nuts
On Oct 17, 12:26 pm, Archos <raul....@sent.com> wrote:
> Why when is assigned a float number to a variable (a := 1.5), it is
> casted auto. to float64 instead of to be casted to float32 (since it's
> a small value)?

Decimal numbers such as 0.1 cannot be expressed accurately in binary
form. So from precision viewpoint, float64 is slightly better than
float32.

j...@webmaster.ms

unread,
Oct 17, 2011, 8:13:24 AM10/17/11
to golan...@googlegroups.com
Also complex128, it seems missed from the manual.

  var aa = 1+2i
  fmt.Printf("%T : %v\n", aa,aa)

Jan Mercl

unread,
Oct 17, 2011, 9:07:49 AM10/17/11
to golan...@googlegroups.com
On Monday, October 17, 2011 2:13:24 PM UTC+2, j...@webmaster.ms wrote:
Also complex128, it seems missed from the manual.

  var aa = 1+2i
  fmt.Printf("%T : %v\n", aa,aa)

Archos

unread,
Oct 17, 2011, 4:57:29 PM10/17/11
to golang-nuts
Then, it is better to use directly float64 instead of float32, isn't
it? Iin our programs that handle float numbers.

Kyle Lemons

unread,
Oct 17, 2011, 5:05:29 PM10/17/11
to Archos, golang-nuts
Then, it is better to use directly float64 instead of float32, isn't
it? Iin our programs that handle float numbers.

Float32 becomes insufficient much faster than you might think.  You don't see "float" very often in C, you almost always see "double."
~K 
Reply all
Reply to author
Forward
0 new messages