Divide 2 big.Floats in go and preserve the resulting decimal

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

Divide 2 big.Floats in go and preserve the resulting decimal

问题

我在Go语言中有两个big.Float类型的数字。

  • x. 93214.310998100256907925
  • y. 1.954478300965909786

我想找出x和y的百分比,应该大约是0.0020967578%。问题在于,当将这两个big float相除时,答案总是0.xxx,但该方法返回的是2.09675776180520477879426e-05。有什么办法可以解决这个问题吗?我尝试过将其转换为字符串再转回来,但这只是另一个我无法解决的问题。我觉得可能有一种方法可以做到这一点,但我可能忽略了。如果需要,我只需要保留7位小数精度。

英文:

I have 2 big.Float numbers in go.

  • x. 93214.310998100256907925
  • y. 1.954478300965909786

I want to find out what percent of x y is. This should be around 0.0020967578%. The issue comes when dividing these 2 big floats the answer is always 0.xxx but the method returns 2.09675776180520477879426e-05. Any ideas to fix this? I have tried converting to a string then back but that isn't another rabbit hole I won't include because I wasn't able to accomplish anything with it. I feel like there is a method to do this I am missing. I really only need 7 decimals of precision of that helps.

答案1

得分: 1

你为什么需要big.Float?即使使用float32似乎也可以满足需求:

package main
import "fmt"

func percent(y, x float32) float32 {
   return y / x * 100
}

func main() {
   p := percent(1.954478300965909786, 93214.310998100256907925)
   fmt.Println(p) // 0.0020967575
}
英文:

Why do you need big.Float? Even float32 seem to be fine:

package main
import "fmt"

func percent(y, x float32) float32 {
   return y / x * 100
}

func main() {
   p := percent(1.954478300965909786, 93214.310998100256907925)
   fmt.Println(p) // 0.0020967575
}

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

发表评论

匿名网友

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

确定