Click here to Skip to main content
15,890,845 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more: , +
C# code rounding result and SQL Sp Rounding result are different when last value is 5

My Code in C#

double meanObject;

double Upper = 1.8415;

meanObject = Math.Round((Convert.ToDouble(Upper)), 3);

==> Result meanObject = 1.842 <==


My Code in SQL SP

Declare @Upper float = 1.8415

select Round(@Upper,3)

==> Result is = 1.841  <==



I want Same Answer in both
Ex.
C# Code =  1.842
SQL SP  =  1.842  (I get the wrong result in SQL SP : 1.841)


What I have tried:


in C# i tried
double meanObject;
double Upper = 1.8415;

meanObject = Math.Round((Convert.ToDouble(Upper)), 3);
Label1.Text = meanObject.ToString(); //Result 1.842


in SQL Sp i Tried

Declare @Upper float = 1.8415

select Round(@Upper,3)


Posted
Updated 25-Jan-19 0:02am
Comments
phil.o 25-Jan-19 4:52am    
Why are you trying to convert to a double value something which is already declared as a double value?
Anuj Mehta 25-Jan-19 5:30am    
I Added it for Just checking code.

Without converting result is same (no change)
double Upper = 1.8415;
double meanObject = Math.Round((Upper), 3);

Result = 1.841

The reason is that .NET uses bankersrounding.

See here[^] or Bankers’ Rounding – Fabulous Adventures In Coding[^]
 
Share this answer
 
Comments
Maciej Los 6-Feb-19 6:44am    
5ed!
Herman<T>.Instance 6-Feb-19 10:51am    
thank you!
Declare @Upper money = 1.8415

select Round(@Upper,3)

Prob Solved using changing datatype to money 
==> SQL Result is = 1.842  <==


Thank You All for responding
 
Share this answer
 
Comments
Maciej Los 6-Feb-19 6:44am    
Great, have a 5!

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