字符串到Float64:单值上下文中的多值strconv.ParseFloat() [英] String to Float64: multiple-value strconv.ParseFloat() in single-value context

查看:3360
本文介绍了字符串到Float64:单值上下文中的多值strconv.ParseFloat()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  [[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]]

请记住,数组不断增加。我只是发布一个示例数组。

现在我将一些浮点数转换为字符串,以便我可以将它附加到字符串切片。但是,我需要对这些数字进行一些数学运算。我想从第二个切片添加字符串编号(5343340.56343)到第三个字符串编号(22139.461201388)。与每个切片中的其他2个浮点数相同。要做到这一点,我需要先将它们转换为float64。获得总和后,我需要将它们转换回字符串,以便我可以将其附加到我的切片,我将弄清楚该怎么做。



转换字符串item to float64,这里是我的:

 用于_,i:=范围数据[1:] {
如果我[0] ==item1{
j:= strconv.ParseFloat(i [4],64)



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


$ b这会给出一个错误:单值上下文中的多值strconv.ParseFloat()
所以我的问题是: / p>


  1. 如何将字符串值转换为Float64。

  2. 可选:关于如何从每个片添加2个浮点数的建议?


任何帮助表示感谢!

解决方案

你得到的错误是因为函数 ParseFloat 返回两个参数,你忽略了第二个。

  j,err:= strconv.ParseFloat(i [4],64)
if err!= nil {
//在此处插入错误处理
}
(...)

尽量在 godocs 之前使用它。


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!

解决方案

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.

这篇关于字符串到Float64:单值上下文中的多值strconv.ParseFloat()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆