将科学计数法转换为十进制数

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

Converting scientific notation to decimal number

问题

我有一个以科学计数法表示的浮点数,为6.316159832682479e-06。将其转换为普通的十进制数(0.000006316159832682479)并保持为float64类型的最佳方法是什么?我需要普通的十进制数进行进一步的计算和API调用。

...
fmt.Printf("%v,%T", ol, ol)
...

打印结果为:6.34e-06, float64

英文:

I have a number stored as a float64 in scientific notation 6.316159832682479e-06 what is the best way to convert this to a normal decimal number (0.000006316159832682479) and still keep it in the float64. I require the normal decimal for further calculations and for an api call.

...
fmt.Printf("%v,%T",ol,ol)
...

Prints: 6.34e-06,float64

答案1

得分: 2

正如其他人指出的那样,您无需将该值转换为任何进一步的计算。您在问题中提供的两个数字描述了相同的float64值。对该数字的任何计算都将产生相同的结果,无论其格式如何。

至于格式化该值的字符串表示,您可以使用strconv.FormatFloat()函数(文档)来完全控制浮点数的格式化方式。

以下示例将以十进制表示打印该数字,不包含任何指数:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	d := 0.000006316159832682479

	fmt.Println(strconv.FormatFloat(d, 'f', -1, 64))
}

还请注意,您还可以使用其他格式字符串使用fmt.Sprintf()来实现类似的结果。有关fmt包的文档,请参阅此处

英文:

As others have pointed out, you do not need to convert the value for any further calculations. Both numbers you provided in your question describe the same float64 value. Any calculation on the number will yield the same result, regardless of its formatting.

As for formatting the string representation of that value, you can use the strconv.FormatFloat() function (docs) to have full control over how the floating-point number is formatted.

The example will print a decimal representation of the number without any exponents:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	d := 0.000006316159832682479

	fmt.Println(strconv.FormatFloat(d, 'f', -1, 64))
}

Note also that you can achieve similar results with fmt.Sprintf() using other format strings. See the documentation for the fmt package here.

huangapple
  • 本文由 发表于 2021年9月6日 01:19:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/69065652.html
匿名

发表评论

匿名网友

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

确定