Go:使用strconv.ParseFloat将字符串转换为浮点数返回0。

huangapple go评论116阅读模式
英文:

Go: converting string to float using strconv.ParseFloat returns 0

问题

我有以下代码:

  1. reader := bufio.NewReader(os.Stdin)
  2. fmt.Print("room: width x length: ")
  3. inStr, _ := reader.ReadString('\n')
  4. result := strings.Split(inStr, "x")
  5. string1, _ := strconv.ParseFloat(result[0], 64)
  6. string2, _ := strconv.ParseFloat(result[1], 64)
  7. fmt.Print(string2)

在最后一个打印语句中,如果我打印string1,它会返回正确的值,但是如果我尝试打印string2,无论我在控制台输入什么值,它都返回0。

有人知道为什么会发生这种情况吗?
谢谢!

英文:

I have the following code:

  1. reader := bufio.NewReader(os.Stdin)
  2. fmt.Print("room: width x length: ")
  3. inStr, _ := reader.ReadString('\n')
  4. result := strings.Split(inStr, "x")
  5. string1, _ := strconv.ParseFloat(result[0], 64)
  6. string2, _ := strconv.ParseFloat(result[1], 64)
  7. fmt.Print(string2)

At the last print statement, if i print string1 it returns the right value, but if i try to print string2 it returns 0, no matter what value i input to the console.

Does anyone know why this is happening?
Thanks!

答案1

得分: 6

将代码中的部分进行翻译如下:

  1. result := strings.Split(inStr, "x")

替换为

  1. result := strings.Split(strings.TrimSpace(inStr), "x")

由于字符串中包含\n,所以第二个数组元素也包含它。

此外,我强烈建议在发布此类问题之前查看错误消息。你可以看到下面的代码的结果是strconv.ParseFloat: parsing "23\n": invalid syntax

  1. string2, err := strconv.ParseFloat(result[1], 64)
  2. if err != nil {
  3. fmt.Println(e)
  4. }
英文:

Replace

  1. result := strings.Split(inStr, "x")

with

  1. result := strings.Split(strings.TrimSpace(inStr), "x")

As string contains \n so your second array element contains it too.

Also I really suggest to look at error messages before posting such kind of questions. You could see strconv.ParseFloat: parsing "23\n": invalid syntax as result of next code

  1. string2, err := strconv.ParseFloat(result[1], 64)
  2. if err != nil {
  3. fmt.Println(e)
  4. }

huangapple
  • 本文由 发表于 2016年4月3日 23:35:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/36387416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定