Skip to content

Commit a4af945

Browse files
committed
Implements System.Decimal support
Convertes System.Decimal to decimal.decimal and vice-versa
1 parent 46d56af commit a4af945

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/runtime/converter.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ private Converter()
3030
private static Type flagsType;
3131
private static Type boolType;
3232
private static Type typeType;
33+
private static IntPtr decimalCtor;
3334

3435
static Converter()
3536
{
@@ -45,6 +46,9 @@ static Converter()
4546
flagsType = typeof(FlagsAttribute);
4647
boolType = typeof(Boolean);
4748
typeType = typeof(Type);
49+
50+
IntPtr decimalMod = Runtime.PyImport_ImportModule("decimal");
51+
if (decimalMod == null) throw new PythonException();
4852
}
4953

5054

@@ -100,6 +104,9 @@ internal static IntPtr GetPythonTypeByAlias(Type op)
100104
if (op == boolType)
101105
return Runtime.PyBoolType;
102106

107+
if (op == decimalType)
108+
return Runtime.PyFloatType;
109+
103110
return IntPtr.Zero;
104111
}
105112

@@ -221,6 +228,14 @@ internal static IntPtr ToPython(object value, Type type)
221228
case TypeCode.UInt64:
222229
return Runtime.PyLong_FromUnsignedLongLong((ulong)value);
223230

231+
case TypeCode.Decimal:
232+
string d2s = ((decimal)value).ToString(nfi);
233+
IntPtr d2p = Runtime.PyString_FromString(d2s);
234+
IntPtr decimalArgs = Runtime.PyTuple_New(1);
235+
Runtime.PyTuple_SetItem(decimalArgs, 0, d2p);
236+
237+
return Runtime.PyObject_CallObject(decimalCtor, decimalArgs);
238+
224239
default:
225240
if (value is IEnumerable)
226241
{
@@ -793,6 +808,18 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo
793808
Runtime.XDecref(op);
794809
result = d;
795810
return true;
811+
812+
case TypeCode.Decimal:
813+
op = Runtime.PyObject_Str(value);
814+
decimal m;
815+
string sm = Runtime.GetManagedString(op);
816+
if (!Decimal.TryParse(sm, NumberStyles.Number, nfi, out m))
817+
{
818+
goto type_error;
819+
}
820+
Runtime.XDecref(op);
821+
result = m;
822+
return true;
796823
}
797824

798825

0 commit comments

Comments
 (0)