round.go 910 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package stats
  2. import "math"
  3. // Round a float to a specific decimal place or precision
  4. func Round(input float64, places int) (rounded float64, err error) {
  5. // If the float is not a number
  6. if math.IsNaN(input) {
  7. return math.NaN(), NaNErr
  8. }
  9. // Find out the actual sign and correct the input for later
  10. sign := 1.0
  11. if input < 0 {
  12. sign = -1
  13. input *= -1
  14. }
  15. // Use the places arg to get the amount of precision wanted
  16. precision := math.Pow(10, float64(places))
  17. // Find the decimal place we are looking to round
  18. digit := input * precision
  19. // Get the actual decimal number as a fraction to be compared
  20. _, decimal := math.Modf(digit)
  21. // If the decimal is less than .5 we round down otherwise up
  22. if decimal >= 0.5 {
  23. rounded = math.Ceil(digit)
  24. } else {
  25. rounded = math.Floor(digit)
  26. }
  27. // Finally we do the math to actually create a rounded number
  28. return rounded / precision * sign, nil
  29. }