summaryrefslogtreecommitdiff
path: root/round.go
blob: d1c625ee50ba7c9aa05b55b0e0096511d1da2cdf (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, places int) float64 {
	scale := math.Pow(10, float64(places))
	abs := math.Abs(v*scale) + 0.5
	return math.Copysign(math.Floor(abs)/scale, v)
}