1
0
Fork 0
mirror of https://github.com/Luzifer/go_helpers.git synced 2024-10-18 06:14:21 +00:00

Added float helpers, moved helpers to subpackages

This commit is contained in:
Knut Ahlers 2016-04-23 14:31:40 +02:00
parent 1626fb35db
commit 880438fb76
Signed by: luzifer
GPG key ID: DC2729FDD34BE99E
6 changed files with 68 additions and 6 deletions

View file

@ -1,4 +1,4 @@
package helpers_test
package float_test
import (
. "github.com/onsi/ginkgo"
@ -7,7 +7,7 @@ import (
"testing"
)
func TestGoHelpers(t *testing.T) {
func TestFloat(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "GoHelpers Suite")
RunSpecs(t, "Float Suite")
}

14
float/round.go Normal file
View file

@ -0,0 +1,14 @@
package float
import "math"
// Round returns a float rounded according to "Round to nearest, ties away from zero" IEEE floaing point rounding rule
func Round(x float64) float64 {
var absx, y float64
absx = math.Abs(x)
y = math.Floor(absx)
if absx-y >= 0.5 {
y += 1.0
}
return math.Copysign(y, x)
}

35
float/round_test.go Normal file
View file

@ -0,0 +1,35 @@
package float_test
import (
"math"
. "github.com/Luzifer/go_helpers/float"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Round", func() {
It("should match the example table of IEEE 754 rules", func() {
Expect(Round(11.5)).To(Equal(12.0))
Expect(Round(12.5)).To(Equal(13.0))
Expect(Round(-11.5)).To(Equal(-12.0))
Expect(Round(-12.5)).To(Equal(-13.0))
})
It("should have correct rounding for numbers near 0.5", func() {
Expect(Round(0.499999999997)).To(Equal(0.0))
Expect(Round(-0.499999999997)).To(Equal(0.0))
})
It("should be able to handle +/-Inf", func() {
Expect(Round(math.Inf(1))).To(Equal(math.Inf(1)))
Expect(Round(math.Inf(-1))).To(Equal(math.Inf(-1)))
})
It("should be able to handle NaN", func() {
Expect(math.IsNaN(Round(math.NaN()))).To(Equal(true))
})
})

View file

@ -1,4 +1,4 @@
package helpers
package str
// AppendIfMissing adds a string to a slice when it's not present yet
func AppendIfMissing(slice []string, s string) []string {

View file

@ -1,7 +1,7 @@
package helpers_test
package str_test
import (
. "github.com/Luzifer/go_helpers"
. "github.com/Luzifer/go_helpers/str"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"

13
str/str_suite_test.go Normal file
View file

@ -0,0 +1,13 @@
package str_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestStr(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Str Suite")
}