4

I have following SQL Server statement, I want to convert this into c#. I know there is something called Math.Round in C#. I have tried but C# returns the same results c# returns an int back. For details please check the Test & results below:

SQL SERVER

Select ROUND(SUM(someValue) / 60,0)  

C#

var alpha = Math.Round(someValue / 60, 0);

Tests & Result

select ROUND(150.75, 0)
-- Result = 151.00

var alpha = Math.Round(150.75, 0);
// Result = 151

Can anyone please suggest me why its not putting .00 in the end. In real values will there be any difference. I am looking ro replace SQL with C#.

Thanks

user1211185
  • 731
  • 3
  • 12
  • 27

2 Answers2

4

As per the table on MSDN here Sql Server's ROUND() will return a decimal output for a decimal input.

The overloads of Math.Round return either decimal or double, depending on the input type.

The reason why you aren't seeing .00 therefore must be as a result of the formatting you are applying to the result.

(Speculative, but the default formatting on string.Format or Debug.Writeline may internally be using a technique such as this to retrieve the number of decimal places and provide a default presentation), e.g.

int count = BitConverter.GetBytes(decimal.GetBits(Math.Round(150.75M, 0))[3])[2];
Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • thanks, will it make in difference with real time values. Because I am planning to replace a logic written in SQL with C#? – user1211185 Apr 11 '14 at 10:45
  • Depends what kind of precision you need - are you working with exact values or can you allow some error at high numbers of DP? – Charleh Apr 11 '14 at 10:47
  • See this post for more info, might clarify which datatype you need (I'm thinking decimal) http://stackoverflow.com/questions/1165761/decimal-vs-double-which-one-should-i-use-and-when – Charleh Apr 11 '14 at 10:49
1

SQL is giving you the same datatype you put in - there is a precision setting for a decimal datatype in SQL and since you are specifying an number with 2dp, SQL returns a value with 2dp.

.NET doesn't share the same data types as SQL and is therefore returning a double (since you didn't specify the input as decimal)

Charleh
  • 13,749
  • 3
  • 37
  • 57