Skip to content

Commit 5780b75

Browse files
authored
Fix numeric formatting patterns by unwrapping scalar values (#3135)
1 parent 539055e commit 5780b75

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/kOS.Safe.Test/Structures/StringValueTest.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,5 +219,16 @@ public void CanParseScientificStrings()
219219
stringTest = new StringValue(" 1.23e+3a ");
220220
Assert.Throws(typeof(Exceptions.KOSNumberParseException), () => stringTest.ToScalar());
221221
}
222+
223+
[Test]
224+
public void CanFormat()
225+
{
226+
var formatString = new StringValue("test1={0:0.0} test2='{0,10:0.0}'");
227+
228+
var expected = new StringValue("test1=13.4 test2=' 13.4'");
229+
var actual = formatString.Format(new ScalarDoubleValue(13.37));
230+
231+
Assert.That(expected.ToString(), Is.EqualTo(actual.ToString()));
232+
}
222233
}
223234
}

src/kOS.Safe/Encapsulation/StringValue.cs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
using kOS.Safe.Serialization;
88
using System.Collections.Generic;
99
using System.Collections;
10+
using System.Linq;
1011

1112
namespace kOS.Safe.Encapsulation
1213
{
@@ -257,7 +258,21 @@ public StringValue Format(params Structure[] args)
257258
{
258259
if (args.Length == 0)
259260
return this;
260-
return new StringValue(string.Format(CultureInfo.InvariantCulture, this, args));
261+
262+
// Unwrap the primitive scalar value and send them
263+
// into String.Format as-is. This is required to allow
264+
// for numeric formatting patterns, like rounding.
265+
var primitiveArgs = args
266+
.Select(arg => {
267+
if (arg is ScalarValue scalar) {
268+
return scalar.ToPrimitive();
269+
}
270+
271+
return arg;
272+
})
273+
.ToArray();
274+
275+
return new StringValue(string.Format(CultureInfo.InvariantCulture, this, primitiveArgs));
261276
}
262277

263278
private void StringInitializeSuffixes()

0 commit comments

Comments
 (0)