使用Golang中的ParseFloat将字符串输入转换为float64

使用Golang中的ParseFloat将字符串输入转换为float64

问题描述:

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("

This program will convert feet to meters for you!
")

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

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

  meters := feetToMeters(feetFloat)

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

我刚刚开始学习Go,我正尝试将字符串从标准输入转换为float64,所以我 可以对输入值进行算术运算。 p>

无论输入值如何,输出都会返回“ 0英尺转换为米,您得到0米”。 在输入上调用ParseFloat之后,我无法弄清楚为什么该值为零。 p>

如果有人可以指出为什么会这样,我将不胜感激。 p>

  const转换float64 = 0.3048 \  n 
func feetToMeters(英尺float64)(米float64){
返回英尺*转换
} 
 
func main(){
 fmt.Println(“ 
 
此程序将为您将英尺转换为米!  
“)
 
读者:= bufio.NewReader(os.Stdin)
 fmt.Println(”输入英尺值:
“)
英尺,_:= reader.ReadString('
')  
 
 feetFloat,_:= strconv.ParseFloat(feet,64)
 
米:= feetToMeters(feetFloat)
 
 fmt.Printf(“%v英尺转换为米会为您提供%v米”,  feetFloat,meters)
} 
  code>  pre> 
  div>

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