Converting string input to float64 using ParseFloat in Golang

一曲冷凌霜 提交于 2020-01-30 08:05:15

问题


I've just started learning Go and I'm trying to convert a string from standard input to a float64 so I can perform an arithmetic operation on the input value.

The output returns "0 feet converted to meters gives you 0 meters" regardless of the input value. I can't figure out why the value is zero after invoking ParseFloat on the input.

If someone could please point out to me why this is happening, I would greatly appreciate it.

const conversion float64 = 0.3048

func feetToMeters (feet float64) (meters float64) {
  return feet * conversion
}

func main(){
  fmt.Println("\n\nThis program will convert feet to meters for you!\n")

  reader := bufio.NewReader(os.Stdin)
  fmt.Println("Enter feet value: \n")
  feet, _ := reader.ReadString('\n')

  feetFloat, _ := strconv.ParseFloat(feet, 64)

  meters := feetToMeters(feetFloat)

  fmt.Printf("%v feet converted to meters give you %v meters",feetFloat,meters)
}

回答1:


The problem is that you try to parse "x.x\n", e.g: 1.8\n. And this returns an error: strconv.ParseFloat: parsing "1.8\n": invalid syntax. You can do a strings.TrimSpace function or to convert feet[:len(feet)-1] to delete \n character

With strings.TrimSpace() (you need to import strings package):

feetFloat, _ := strconv.ParseFloat(strings.TrimSpace(feet), 64)

Wtih feet[:len(feet)-1]:

feetFloat, _ := strconv.ParseFloat(feet[:len(feet)-1], 64)

Output in both cases:

10.8 feet converted to meters give you 3.2918400000000005 meters


来源:https://stackoverflow.com/questions/38777961/converting-string-input-to-float64-using-parsefloat-in-golang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!