summaryrefslogtreecommitdiff
path: root/ftoa_test.go
blob: e5076c45ef60c790e74059ebb1b16b5c376e6031 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package humanize

import (
	"fmt"
	"regexp"
	"strconv"
	"testing"
)

func TestFtoa(t *testing.T) {
	testList{
		{"200", Ftoa(200), "200"},
		{"2", Ftoa(2), "2"},
		{"2.2", Ftoa(2.2), "2.2"},
		{"2.02", Ftoa(2.02), "2.02"},
		{"200.02", Ftoa(200.02), "200.02"},
	}.validate(t)
}

func TestFtoaWithDigits(t *testing.T) {
	testList{
		{"1.23, 0", FtoaWithDigits(1.23, 0), "1"},
		{"1.23, 1", FtoaWithDigits(1.23, 1), "1.2"},
		{"1.23, 2", FtoaWithDigits(1.23, 2), "1.23"},
		{"1.23, 3", FtoaWithDigits(1.23, 3), "1.23"},
	}.validate(t)
}

func BenchmarkFtoaRegexTrailing(b *testing.B) {
	trailingZerosRegex := regexp.MustCompile(`\.?0+$`)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		trailingZerosRegex.ReplaceAllString("2.00000", "")
		trailingZerosRegex.ReplaceAllString("2.0000", "")
		trailingZerosRegex.ReplaceAllString("2.000", "")
		trailingZerosRegex.ReplaceAllString("2.00", "")
		trailingZerosRegex.ReplaceAllString("2.0", "")
		trailingZerosRegex.ReplaceAllString("2", "")
	}
}

func BenchmarkFtoaFunc(b *testing.B) {
	for i := 0; i < b.N; i++ {
		stripTrailingZeros("2.00000")
		stripTrailingZeros("2.0000")
		stripTrailingZeros("2.000")
		stripTrailingZeros("2.00")
		stripTrailingZeros("2.0")
		stripTrailingZeros("2")
	}
}

func BenchmarkFmtF(b *testing.B) {
	for i := 0; i < b.N; i++ {
		_ = fmt.Sprintf("%f", 2.03584)
	}
}

func BenchmarkStrconvF(b *testing.B) {
	for i := 0; i < b.N; i++ {
		strconv.FormatFloat(2.03584, 'f', 6, 64)
	}
}