tools.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package util
  2. import (
  3. "math"
  4. "math/big"
  5. )
  6. // Div div
  7. func Div(x, y float64) float64 {
  8. a := big.NewFloat(x)
  9. b := big.NewFloat(y)
  10. c := new(big.Float).Quo(a, b)
  11. d, _ := c.Float64()
  12. return d
  13. }
  14. // Mul mul
  15. func Mul(x, y float64) float64 {
  16. a := big.NewFloat(x)
  17. b := big.NewFloat(y)
  18. c := new(big.Float).Mul(a, b)
  19. d, _ := c.Float64()
  20. return d
  21. }
  22. // DivWithRound div with round
  23. func DivWithRound(x, y float64, places int) float64 {
  24. a := big.NewFloat(x)
  25. b := big.NewFloat(y)
  26. c := new(big.Float).Quo(a, b)
  27. d, _ := c.Float64()
  28. return Round(d, places)
  29. }
  30. // MulWithRound mul with round
  31. func MulWithRound(x, y float64, places int) float64 {
  32. a := big.NewFloat(x)
  33. b := big.NewFloat(y)
  34. c := new(big.Float).Mul(a, b)
  35. d, _ := c.Float64()
  36. return Round(d, places)
  37. }
  38. // Round round
  39. func Round(val float64, places int) float64 {
  40. var round float64
  41. pow := math.Pow(10, float64(places))
  42. digit := pow * val
  43. _, div := math.Modf(digit)
  44. if div >= 0.5 {
  45. round = math.Ceil(digit)
  46. } else {
  47. round = math.Floor(digit)
  48. }
  49. return round / pow
  50. }