Click here to Skip to main content
16,018,797 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Does math.round in C# and sql server are the same.
I have check the following, but I didn't understand how the Math.Round function is working in C#.
Sql Server:
select convert(varchar,convert(numeric(18,2),224.025000000 )) Output 224.03

C#:
Math.Round(224.025000000)) Output 224.02
But
Math.Round(2.345, 2) Output 2.35
Math.Round(2.245, 2) Output 2.24

Can anybody tell Why the outputs of above two statements are different ?

Thanks in advance.
Posted
Comments
Henry.Ayoola 12-Aug-11 3:30am    
Short answer: because the inputs are different. numeric(18,2) isn't the same type as double.

Use this
C#
Math.Round(224.02500000, 2,MidpointRounding.AwayFromZero)

Ref:http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx[^]
 
Share this answer
 
Comments
Gopi9999 12-Aug-11 2:22am    
Thank you very much. It solved my problem...
Prerak Patel 12-Aug-11 2:24am    
You are welcome.
From MSDN (http://msdn.microsoft.com/en-us/library/75ks3aby.aspx[^]):
Notes to Callers
Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32) method may not appear to round midpoint values to the nearest even value in the digits decimal position. This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14. This occurs because internally the method multiplies value by 10 * digits, and the multiplication operation in this case suffers from a loss of precision.
 
Share this answer
 
Hi Gopi,

Please use ROUND (Transact-SQL) to achive this.
 
Share this answer
 
Comments
Gopi9999 12-Aug-11 2:11am    
Hi, Thanks for reply.
Even if I use Round, I am facing the same problem
select round(224.025,2) Output 224.030 and it is rounding to 224.02 in c#.
I want both values to be equal. What to do...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900