如何将字符串转换为浮点数。

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

How to convert string to float number

问题

这是我的 playground 链接。
我有一个字符串数组,里面存放着一些数字。我尝试将它们转换为浮点数,但是没有得到任何结果。这段代码有什么问题?

var numbers []float64

for _, elem := range str_numbers {
	i, err := strconv.ParseFloat(elem, 64)
	if err != nil {
		numbers = append(numbers, i)
	}
}
fmt.Println(numbers)	
    // 这段代码输出的是空数组  []
英文:

http://play.golang.org/p/7kR2uZlV5-

This is my playground link.
I have an array of numbers but in string. I tried to convert them to float number but it does not give me anything. What is wrong with it?

var numbers []float64

for _, elem := range str_numbers {
	i, err := strconv.ParseFloat(elem, 64)
	if err != nil {
		numbers = append(numbers, i)
	}
}
fmt.Println(numbers)	
    // this gives me nothing  []

答案1

得分: 27

将代码中的

if err != nil {

改为

if err == nil {

(你可能已经在做这个了,但是unit testing是捕捉此类错误的好方法。)

英文:

Change

if err != nil {

to

if err == nil {

(You may be doing this already, but unit testing is a great way to catch bugs like this.)

huangapple
  • 本文由 发表于 2013年10月7日 08:09:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/19215435.html
匿名

发表评论

匿名网友

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

确定