LaSul
LaSul

Reputation: 2421

Convert float64 array to float32 array

I have an array of float64 and want to convert each value to float32.

I've tried:

# What I have 
features64 [120]float64

# What I've tried
features32 = [120]float32(features64)

But that gives the compile error:

cannot convert features (type [120]float64) to type [120]float32

Upvotes: 4

Views: 2728

Answers (3)

peterSO
peterSO

Reputation: 166704

For example,

package main

func main() {
    var features64 [120]float64

    var features32 [len(features64)]float32
    for i, f64 := range features64 {
        features32[i] = float32(f64)
    }
}

Upvotes: 3

KibGzr
KibGzr

Reputation: 2093

Simply

var arr1 [120]float64
var arr2 [120]float32
for i, v := range arr1 {
    arr2[i] = float32(v)
}

Upvotes: 2

Adrian
Adrian

Reputation: 46532

You can't convert one slice/array type to another. You'll need to create a new array and iterate over the original converting each element:

for i,f := range features64 {
    features32[i] = float32(f)
}

Upvotes: 3

Related Questions