diff --git a/CHANGELOG.md b/CHANGELOG.md index 953c2cfd7..62d640b16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ### C# -> VB * Don't emit Me on the first parameter of an extension method - [#1118](https://github.com/icsharpcode/CodeConverter/issues/1118) +* Truncate towards zero when converting a fractional number to an integer, instead of inheriting VB's rounding - [#1021](https://github.com/icsharpcode/CodeConverter/issues/1021) ## [10.0.2] - 2026-11-08 diff --git a/CodeConverter/VB/NodesVisitor.cs b/CodeConverter/VB/NodesVisitor.cs index 9e949784c..cc18974bf 100644 --- a/CodeConverter/VB/NodesVisitor.cs +++ b/CodeConverter/VB/NodesVisitor.cs @@ -1442,8 +1442,16 @@ public override VisualBasicSyntaxNode VisitCastExpression(CSSyntax.CastExpressio Func toNumber = kind => { if (sourceType?.SpecialType == SpecialType.System_Char) return SyntaxFactory.InvocationExpression(SyntaxFactory.ParseName(GetQualifiedName(nameof(Microsoft), nameof(Microsoft.VisualBasic), nameof(Microsoft.VisualBasic.Strings.AscW))), ExpressionSyntaxExtensions.CreateArgList(expr)); - return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(kind), expr); + var operand = destType.IsIntegralType() ? TruncateFractionalSource(expr, sourceType) : expr; + return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(kind), operand); }; + + // The C# compiler has already truncated the operand, and a method call can't appear in a constant expression + var constantValue = _semanticModel.GetConstantValue(node); + if (destType.IsIntegralType() && sourceType.IsFractionalNumericType() && constantValue.HasValue) { + return _commonConversions.Literal(constantValue.Value); + } + switch (destType.SpecialType) { case SpecialType.System_Object: return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(SyntaxKind.CObjKeyword), expr); @@ -1484,6 +1492,18 @@ public override VisualBasicSyntaxNode VisitCastExpression(CSSyntax.CastExpressio } } + /// + /// C# truncates towards zero when converting a fractional number to an integer, whereas VB rounds. The cast is kept + /// around the call because it fixes the type of the expression (e.g. when it is boxed); the VB simplifier removes it + /// wherever the target type converts implicitly. + /// + private static ExpressionSyntax TruncateFractionalSource(ExpressionSyntax expr, ITypeSymbol sourceType) + { + return sourceType.IsFractionalNumericType() + ? SyntaxFactory.InvocationExpression(SyntaxFactory.ParseName(GetQualifiedName(nameof(System), nameof(Math), nameof(Math.Truncate))), ExpressionSyntaxExtensions.CreateArgList(expr)) + : expr; + } + public override VisualBasicSyntaxNode VisitObjectCreationExpression(CSSyntax.ObjectCreationExpressionSyntax node) { return SyntaxFactory.ObjectCreationExpression( diff --git a/Tests/TestData/SelfVerifyingTests/CSToVB/TruncatingCasts.cs b/Tests/TestData/SelfVerifyingTests/CSToVB/TruncatingCasts.cs new file mode 100644 index 000000000..19f0a768b --- /dev/null +++ b/Tests/TestData/SelfVerifyingTests/CSToVB/TruncatingCasts.cs @@ -0,0 +1,27 @@ +using Xunit; + +public partial class TruncatingCasts +{ + [Fact] + public static void TruncatesTowardsZero() + { + double positive = 0.6d; + double negative = -0.6d; + double aboveOne = 1.9d; + decimal decimalValue = 2.9m; + + Assert.Equal(0, (int)positive); + Assert.Equal(0, (int)negative); + Assert.Equal(1, (int)aboveOne); + Assert.Equal(-1, (int)-aboveOne); + Assert.Equal(0, Truncated(negative)); + + long truncatedDecimal = (long)decimalValue; + Assert.Equal(2L, truncatedDecimal); + } + + private static int Truncated(double value) + { + return (int)value; + } +} diff --git a/Tests/VB/SpecialConversionTests.cs b/Tests/VB/SpecialConversionTests.cs index c38ece9e7..5c4346f5d 100644 --- a/Tests/VB/SpecialConversionTests.cs +++ b/Tests/VB/SpecialConversionTests.cs @@ -33,7 +33,7 @@ internal partial class TestClass }", @"Imports System Friend Partial Class TestClass - Private GENERIC_READ As Integer = Math.Pow(46341, 2) + Private GENERIC_READ As Integer = Math.Truncate(Math.Pow(46341, 2)) End Class WARNING: Expression at character 85 contained the checked keyword before conversion"); } diff --git a/Tests/VB/TypeCastTests.cs b/Tests/VB/TypeCastTests.cs index aad004b08..ff716ab13 100644 --- a/Tests/VB/TypeCastTests.cs +++ b/Tests/VB/TypeCastTests.cs @@ -211,4 +211,56 @@ Public Sub TestMethod(o As Object) End Sub End Class"); } -} \ No newline at end of file + + [Fact] + public async Task CastFractionalToInteger_TruncatesTowardsZeroAsync() + { + await TestConversionCSharpToVisualBasicAsync( + @"using System; + +public partial class A +{ + public static void Main() + { + double foo = 0.6d; + int bar = (int)foo; + int baz = (int)Math.Ceiling(foo); + Console.WriteLine(bar); + Console.WriteLine(baz); + } +}", + @"Imports System + +Public Partial Class A + Public Shared Sub Main() + Dim foo = 0.6R + Dim bar As Integer = Math.Truncate(foo) + Dim baz As Integer = Math.Truncate(Math.Ceiling(foo)) + Console.WriteLine(bar) + Console.WriteLine(baz) + End Sub +End Class"); + } + + [Fact] + public async Task CastFractionalToInteger_TruncatedConstantAndBoxedValueAsync() + { + await TestConversionCSharpToVisualBasicAsync( + @"public class A +{ + const int TruncatedConstant = (int)0.6; + void Test(double d, decimal m) + { + object boxed = (int)d; + long fromDecimal = (long)m; + } +}", + @"Public Class A + Const TruncatedConstant As Integer = 0 + Private Sub Test(d As Double, m As Decimal) + Dim boxed As Object = CInt(Math.Truncate(d)) + Dim fromDecimal As Long = Math.Truncate(m) + End Sub +End Class"); + } +}