Charan Reddy
Charan Reddy

Reputation: 524

constant truncated to integer error during type conversion of float constant to int

The following code is raising the error "Constant truncated to integer " on the line "var a int = int(1.333)".I am new to GO and not able to figure out the actual problem.

package main

import (
    "fmt"
    "math"
)

func main() {
    var x, y int = 3, 4
    const k float64=2.2
    var a int = int(1.333)
    var f float64 = math.Sqrt(float64(x*x+y*y))
    var z uint = uint(f)
    fmt.Println(x, y, z,a)
}

Upvotes: 0

Views: 4190

Answers (1)

mkopriva
mkopriva

Reputation: 38203

The conversion of constants follows different rules than the conversion of non-constants.

First non-constants:

Conversions between numeric types

For the conversion of non-constant numeric values, the following rules apply:

  1. ...
  2. When converting a floating-point number to an integer, the fraction is discarded (truncation towards zero).
  3. ...

So this is possible:

var f = float64(1.333)
var i = int(f)

Now constants:

A constant value x can be converted to type T if x is representable by a value of T.

Then, in the documentation, there's a list of example expressions, one of them being this:

int(1.2) // illegal: 1.2 cannot be represented as an int

On representability

A constant x is representable by a value of type T if one of the following conditions applies:

  • x is in the set of values determined by T.
  • T is a floating-point type and x can be rounded to T's precision without overflow. Rounding uses IEEE 754 round-to-even rules but with an IEEE negative zero further simplified to an unsigned zero. Note that constant values never result in an IEEE negative zero, NaN, or infinity.
  • T is a complex type, and x's components real(x) and imag(x) are representable by values of T's component type (float32 or float64).

None of the 3 conditions applies to the expression var a int = int(1.333) and therefore it is illegal.


Read more about Conversions and Representability

Upvotes: 3

Related Questions