英文:
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.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论