C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: We have a float of value 1.2. When cast to an int, we are left with 1—the numbers after the decimal place are dropped.
Quote: When converting a floating-point number to an integer, the fraction is discarded (truncation towards zero) (Go Language Specification).
Golang program that casts float to int
package main
import "fmt"
func main() {
size := 1.2
fmt.Println(size)
// Convert to an int with a cast.
i := int(size)
fmt.Println(i)
}
Output
1.2
1
Tip: For simple cases (like when numbers are base 10, as they usually are) the Itoa and Atoi methods are typically clearer.
Golang program that converts strings, ints with Itoa
package main
import (
"fmt"
"strconv"
)
func main() {
value := 120
// Use Itoa to convert int to string.
result := strconv.Itoa(value)
fmt.Println(result)
if result == "120" {
fmt.Println(true)
}
// Use Atoi to convert string to int.
original, _ := strconv.Atoi(result)
if original == 120 {
fmt.Println(true)
}
}
Output
120
true
true
Golang program that converts slice to string
package main
import (
"fmt"
"strings"
)
func main() {
// Slice of 3 strings.
values := []string{"fish", "chicken", "lettuce"}
// Convert slice into a string.
result := strings.Join(values, ",");
fmt.Println(result)
}
Output
fish,chicken,lettuce
Tip: The runes here can be manipulated like any other element in a slice. This allows us to modify strings in many ways.
Golang program that converts string to rune slice
package main
import "fmt"
func main() {
// An example string.
value := "cat"
fmt.Println(value)
// Convert string into a slice of runes.
slice := []rune(value)
fmt.Println(slice)
// Convert rune slice into a string.
original := string(slice)
fmt.Println(original)
}
Output
cat
[99 97 116]
cat