Skip to content

Commit 647f042

Browse files
authored
Use invariant culture when converting float constant to string (#245)
* Use invariant culture when converting float constant to string * Fix formatting * Use number in thousands + fraction (distance to moon in km)
1 parent c21d30d commit 647f042

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

src/CSnakes.SourceGeneration/Parser/Types/PythonConstant.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
namespace CSnakes.Parser.Types;
1+
using System.Globalization;
2+
3+
namespace CSnakes.Parser.Types;
24

35
public abstract class PythonConstant
46
{
@@ -23,7 +25,7 @@ public sealed class BinaryInteger(long value) : Integer(value)
2325
public sealed class Float(double value) : PythonConstant
2426
{
2527
public double Value { get; } = value;
26-
public override string ToString() => Value.ToString();
28+
public override string ToString() => Value.ToString(CultureInfo.InvariantCulture);
2729
}
2830

2931
public sealed class String(string value) : PythonConstant
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using CSnakes.Parser.Types;
2+
using System.Globalization;
3+
4+
namespace CSnakes.Tests;
5+
public class PythonConstantTests
6+
{
7+
public sealed class FloatTests
8+
{
9+
[Fact]
10+
public void ToString_Is_Not_Culture_Specific()
11+
{
12+
var testCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone();
13+
testCulture.NumberFormat.NumberDecimalSeparator = ",";
14+
testCulture.NumberFormat.NumberGroupSeparator = ".";
15+
16+
var oldCulture = CultureInfo.CurrentCulture;
17+
CultureInfo.CurrentCulture = CultureInfo.ReadOnly(testCulture);
18+
19+
try
20+
{
21+
var n = new PythonConstant.Float(1_737.4);
22+
Assert.Equal("1737.4", n.ToString());
23+
}
24+
finally
25+
{
26+
CultureInfo.CurrentCulture = oldCulture;
27+
}
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)