[Golang] Type Conversion between String and Floating Number
Example of Go type conversion (type casting) between string and floating number (float64).
Problem
Assume we have the following two variable of type string:
width := "560"
height := "315"
We want to calculate the aspect ratio, i.e., width/height, and then represent the ratio as percents using the symbol %.
The final result will be (of type string):
56.25%
Solution
- Convert string to float64:
- Convert float64 to string:
The following code convert string to float64, calculate aspect ratio, and then convert the float64 result back to string.
package main
import (
"fmt"
"strconv"
)
func main() {
width := "560"
height := "315"
// convert string to float64
w, err := strconv.ParseFloat(width, 64)
if err != nil {
fmt.Println(err)
}
h, err := strconv.ParseFloat(height, 64)
if err != nil {
fmt.Println(err)
}
// make calculation and then convert float64 to string
aspectRatio := strconv.FormatFloat(h*100/w, 'f', -1, 64) + "%"
fmt.Println("aspect ratio: ", aspectRatio)
}
References:
[1] |
[2] | func ParseFloat - strconv - The Go Programming Language |
[3] |
[4] | func FormatFloat - strconv - The Go Programming Language |