Handle float --> int conversions more like we'd expect

This commit is contained in:
Deukhoofd 2018-12-11 16:10:08 +01:00
parent e57129e116
commit 590614c34d
No known key found for this signature in database
GPG Key ID: B4C087AC81641654
1 changed files with 14 additions and 2 deletions

View File

@ -130,19 +130,31 @@ namespace Upsilon.BaseTypes.UserData
return s.Value; return s.Value;
} }
break; break;
case TypeCode.Byte: case TypeCode.Single:
case TypeCode.Decimal: case TypeCode.Decimal:
case TypeCode.Double: case TypeCode.Double:
if (value is ScriptNumber number)
{
return Convert.ChangeType(number.ToCSharpObject(), typeCode);
}
break;
case TypeCode.Byte:
case TypeCode.Int16: case TypeCode.Int16:
case TypeCode.Int32: case TypeCode.Int32:
case TypeCode.Int64: case TypeCode.Int64:
case TypeCode.SByte: case TypeCode.SByte:
case TypeCode.Single:
case TypeCode.UInt16: case TypeCode.UInt16:
case TypeCode.UInt32: case TypeCode.UInt32:
case TypeCode.UInt64: case TypeCode.UInt64:
if (value is ScriptNumber numeric) if (value is ScriptNumber numeric)
{ {
if (numeric.IsFloat)
{
// We expect a conversion from a float to an integer to just lose its precision, however
// Convert.ChangeType will round it to the nearest integer. Therefore we floor the value
// before converting it
return Convert.ChangeType(Math.Floor((double) numeric.ToCSharpObject()), typeCode);
}
return Convert.ChangeType(numeric.ToCSharpObject(), typeCode); return Convert.ChangeType(numeric.ToCSharpObject(), typeCode);
} }
break; break;