将字符串转换为Float64:在单值上下文中的多值strconv.ParseFloat()。

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

String to Float64: multiple-value strconv.ParseFloat() in single-value context

问题

我有一个类似这样的字符串切片数组:

[[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)相加。对于每个切片中的其他两个浮点数也是同样的操作。为了实现这一点,我首先需要将它们转换为float64类型。在得到总和之后,我需要将它们再次转换为字符串,以便将其附加到我的切片中(我将找出如何实现这一点)。

要将字符串项转换为float64类型,我有以下代码:

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
}

这会报错:multiple-value strconv.ParseFloat() in single-value context
所以我的问题是:

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

  2. 可选:有关如何将每个切片中的两个浮点数相加的建议?

感谢任何帮助!

英文:

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

得分: 15

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

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

在使用之前,尝试始终在godocs中检查函数的签名。

英文:

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.

huangapple
  • 本文由 发表于 2017年2月10日 04:41:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/42146467.html
匿名

发表评论

匿名网友

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

确定