From cf6b4f08f0669d231d5e0e2a21b694191da64c88 Mon Sep 17 00:00:00 2001 From: Marc-Antoine Ruel Date: Fri, 6 Apr 2018 20:20:15 -0400 Subject: [PATCH] devices: stop using fmt for units Use strconv directly instead. --- devices/units.go | 18 +++++++++++++++--- devices/units_test.go | 8 ++++---- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/devices/units.go b/devices/units.go index 9c225be..43f229c 100644 --- a/devices/units.go +++ b/devices/units.go @@ -5,7 +5,7 @@ package devices import ( - "fmt" + "strconv" ) // Milli is a fixed point value with 0.001 precision. @@ -22,7 +22,7 @@ func (m Milli) String() string { if d < 0 { d = -d } - return fmt.Sprintf("%d.%03d", m/1000, d) + return strconv.Itoa(int(m)/1000) + "." + prefixZeros(3, int(d)) } // Celsius is a temperature at a precision of 0.001°C. @@ -87,5 +87,17 @@ func (r RelativeHumidity) String() string { if m < 0 { m = -m } - return fmt.Sprintf("%d.%02d%%rH", r/100, m) + return strconv.Itoa(int(r)/100) + "." + prefixZeros(2, int(m)) + "%rH" +} + +// + +func prefixZeros(digits, v int) string { + // digits is expected to be around 2~3. + s := strconv.Itoa(v) + for len(s) < digits { + // O(n²) but since digits is expected to run 2~3 times at most, it doesn't matter. + s = "0" + s + } + return s } diff --git a/devices/units_test.go b/devices/units_test.go index 180d990..5a98830 100644 --- a/devices/units_test.go +++ b/devices/units_test.go @@ -60,11 +60,11 @@ func TestKPascal(t *testing.T) { } func TestRelativeHumidity(t *testing.T) { - o := RelativeHumidity(5010) - if s := o.String(); s != "50.10%rH" { + o := RelativeHumidity(5006) + if s := o.String(); s != "50.06%rH" { t.Fatalf("%#v", s) } - if f := o.Float64(); f > 50.11 || f < 50.09 { + if f := o.Float64(); f >= 50.07 || f <= 50.05 { t.Fatalf("%f", f) } } @@ -74,7 +74,7 @@ func TestRelativeHumidity_neg(t *testing.T) { if s := o.String(); s != "-50.10%rH" { t.Fatalf("%#v", s) } - if f := o.Float64(); f < -50.11 || f > -50.09 { + if f := o.Float64(); f <= -50.11 || f >= -50.09 { t.Fatalf("%f", f) } }