问题
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:
How can I convert the string value to Float64.
Optional: Any suggestions on how I can add the 2 float numbers from each slice?
Any help is appreciated!
回答1:
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.
来源:https://stackoverflow.com/questions/42146467/string-to-float64-multiple-value-strconv-parsefloat-in-single-value-context