Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

.net - Why Round(Fix(x))?

In the Reflector extract for Microsoft.VisualBasic it references Microsoft.VisualBasic.Conversion.Fix in 3 places not including the Fix(Object) overload.

In each case it applies Math.Round to the result. (Especially in DateAdd and DateDiff; the third use in Choose does subtract 1, and redundantly cast to Double again before applying Round.)

When can Math.Round(Conversion.Fix(x)) <> Conversion.Fix(x) for Double x?

(I'd check the Reference Source myself but I can't find a download that does include Microsoft.VisualBasic.) Reference Source now available online.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All of these references are then cast to Integer or Long:

CInt and CLng explicitly call Math.Round before their corresponding IL conv.ovf.i4/8 cast when casting from Single and Double.

This enforces the Banker's Rounding that is a VB.NET known "quirk".

conv.ovf.i4 alone truncates towards zero, which happens to be the same as Fix (for the numbers that fit in an Integer, or a Long for conv.ovf.i8).

(When I originally typed in the question I thought I had checked that this was not the cause.)

For a while, Microsoft made the Reference Source available, so I was able to confirm they were all enclosed in CInt or CLng and the Math.Round is added by the compiler.

The VB.NET "source" currently available at the above link now only provides the "reference assembly" which has no code :-(


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...