Skip to content

Commit 816b797

Browse files
committed
Improve formatting of floats.
Signed-off-by: Felix Fontein <[email protected]>
1 parent 2e2d7d9 commit 816b797

File tree

3 files changed

+16
-7
lines changed

3 files changed

+16
-7
lines changed

functional-tests/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ bar: baz
306306
assert!(
307307
data == "[the_section]
308308
int = 123
309-
float = 1.230000
309+
float = 1.23
310310
bool = true
311311
date = 2025-01-02T00:00:00Z
312312
timestamp = 2025-01-02T03:04:05Z

stores/ini/store.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,12 @@ func (store Store) stripCommentChar(comment string) string {
8282
func (store Store) valToString(v interface{}) string {
8383
switch v := v.(type) {
8484
case float64:
85-
return strconv.FormatFloat(v, 'f', 6, 64)
85+
result := strconv.FormatFloat(v, 'G', -1, 64)
86+
// If the result can be confused with an integer, make sure we have at least one decimal digit
87+
if !strings.ContainsRune(result, '.') && !strings.ContainsRune(result, 'E') {
88+
result = strconv.FormatFloat(v, 'f', 1, 64)
89+
}
90+
return result
8691
case bool:
8792
return strconv.FormatBool(v)
8893
case time.Time:

stores/ini/store_test.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,15 @@ func TestUnmarshalMetadataFromNonSOPSFile(t *testing.T) {
187187
func TestValToString(t *testing.T) {
188188
store := Store{}
189189
assert.Equal(t, "1", store.valToString(1))
190-
assert.Equal(t, "1.000000", store.valToString(1.0))
191-
assert.Equal(t, "-20000000000.000000", store.valToString(-2e10))
192-
assert.Equal(t, "0.000000", store.valToString(2e-10))
193-
assert.Equal(t, "12345000000000000583883634749019137936624068583482471750845213260941541453980911162485633595979333632.000000", store.valToString(1.2345e100))
194-
assert.Equal(t, "0.000000", store.valToString(1.2345e-100))
190+
assert.Equal(t, "1.0", store.valToString(1.0))
191+
assert.Equal(t, "1.1", store.valToString(1.10))
192+
assert.Equal(t, "1.23", store.valToString(1.23))
193+
assert.Equal(t, "1.2345678901234567", store.valToString(1.234567890123456789))
194+
assert.Equal(t, "200000.0", store.valToString(2E5))
195+
assert.Equal(t, "-2E+10", store.valToString(-2E10))
196+
assert.Equal(t, "2E-10", store.valToString(2E-10))
197+
assert.Equal(t, "1.2345E+100", store.valToString(1.2345E100))
198+
assert.Equal(t, "1.2345E-100", store.valToString(1.2345E-100))
195199
assert.Equal(t, "true", store.valToString(true))
196200
assert.Equal(t, "false", store.valToString(false))
197201
ts, _ := time.Parse(time.RFC3339, "2025-01-02T03:04:05Z")

0 commit comments

Comments
 (0)