From 64a507e2f19fc1ed9dab7f8123b334067d107533 Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Sun, 21 May 2017 15:02:35 +0200 Subject: initial import --- round.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 round.go (limited to 'round.go') diff --git a/round.go b/round.go new file mode 100644 index 0000000..89725f2 --- /dev/null +++ b/round.go @@ -0,0 +1,18 @@ +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 + +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) +} + +// Round a float value to 2 decimal places +func Round(v float64) float64 { + return round(v, 2) +} -- cgit v1.2.3