summaryrefslogtreecommitdiff
path: root/round.go
blob: 345f7b0fb6de83f1453c2529a0a6f2205b179935 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package float

import "math"

// ISO 80000-1:2012
// q =  \sgn(y) \left\lfloor \left| y \right| + 0.5 \right\rfloor
//   = -\sgn(y) \left\lceil -\left| y \right| - 0.5 \right\rceil

// Round a float value to n decimal places
func Round(v float64, n int) float64 {
	pow := math.Pow(10, float64(n))
	abs := math.Abs(v*pow) + 0.5
	return math.Copysign(math.Floor(abs)/pow, v)
}