普通网友 2017-02-09 20:41
浏览 298
已采纳

字符串到Float64:单值上下文中的多值strconv.ParseFloat()

I have an array of STRING slices like this:

[[header1 header2 startdate enddate header3 header4] 
[item1 100 01/01/2017 02/01/2017 5343340.56343 3.77252223956] 
[item2 554 01/01/2017 02/01/2017 22139.461201388 17.232284405]]

Keep in mind that the array keeps on increasing. I am just posting a sample array.

Now I converted some of the float numbers to string so that I could append it to the string slices. However, I need to do some math with those numbers. I want to add the string number(5343340.56343) from the 2nd slice to 3rd string number (22139.461201388). Same thing with the other 2 float numbers in each slices. To do that, I need to first convert them to float64. After getting the sum, I will need to convert them back to string so I can append it to my slice which I will figure out how to do.

To convert the string item to float64, here's what I have:

for _, i := range data[1:] {
    if i[0] == "item1" {
        j := strconv.ParseFloat(i[4], 64)


    }
    if i[0] == "item2" {
        k := strconv.ParseFloat(i[4], 64)
    }
    sum := j + k
}

This gives an error: multiple-value strconv.ParseFloat() in single-value context So my question is:

  1. How can I convert the string value to Float64.

  2. Optional: Any suggestions on how I can add the 2 float numbers from each slice?

Any help is appreciated!

  • 写回答

1条回答 默认 最新

  • dpp42324 2017-02-09 20:44
    关注

    The error you are getting is because the function ParseFloat returns two arguments and you are ignoring the second.

    j, err := strconv.ParseFloat(i[4], 64)
    if err != nil {
      // insert error handling here
    }
    (...)
    

    Try to always check the function's signature in godocs before using it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?