Reputation: 955
I am new to Go and I am a bit stuck on a problem regarding human height conversion from feet/inches to cm.
How can I convert, in an efficient way, a string that looks like this 5'2''
to an centimeter int?
Edit: After some more testing I ended up with this solution. How can it be improved?
height := strings.Split("5'2''", "'")
heightfeet,err :=strconv.ParseFloat(height[0],10)
heightinch,err :=strconv.ParseFloat(height[1],10)
heightcm :=heightfeet*30.48+heightinch*2.54
Upvotes: 1
Views: 1240
Reputation: 3985
I feel like your approach is fine, but, if you actually want to be sure to extract only the integers and using constants take a look at this Go Playground I set up.
package main
import (
"fmt"
"regexp"
"strconv"
)
func main() {
//Defining our constants
const cm1 = 30.48
const cm2 = 2.54
//Slice to contain parsed ints
var parsedTokens []float64
feet := "5'2''"
//Regex to extract only integers
reg := regexp.MustCompile("[0-9]+")
filtered:= reg.FindAllString(feet, -1)
//Parse each value v in filtered and append it into parsedTokens
for _, v := range filtered {
k, _ := strconv.ParseFloat(v, 64)
parsedTokens = append(parsedTokens, k)
}
//157.48000000000002
fmt.Println(parsedTokens[0]*cm1 + parsedTokens[1]*cm2)
}
Upvotes: 3