Recent PostsRecent Posts Popular TopicsPopular Topics
 Home Search Members Calendar Who's On

 differences in rounding / converting strings Rate Topic Display Mode Topic Options
Author
 Message
 Posted Monday, December 9, 2013 9:11 AM
 SSC-Enthusiastic Group: General Forum Members Last Login: Saturday, November 26, 2016 1:04 PM Points: 153, Visits: 398
 Hi all,first of all: I know some best practices and work-arounds when working with float numbers, I just want to understand :)An older topic tried to explain the difference between`SELECT ROUND ('6.465',2) --- result 6.46`and`SELECT ROUND (6.465,2) --- result 6.47`withIt's because you're relying on an implicit conversion from a string to a decimal data type which SQL server will do to 2 decimal places by default...Allright:`SELECT ROUND (CONVERT(DECIMAL(3,2),'6.465'),2) --- result 6.47`Now please explain this:`SELECT ROUND('0.285',2) -- 0.28SELECT ROUND(0.285,2) -- 0.29SELECT ROUND (CONVERT(DECIMAL(3,2),'0.285'),2) --- result 0.29`The string value does not seem to be converted to decimal with 2 decimal places.MS is on the safe side with mentioning the last digit is always an estimateBut because the result of the estimate is always the same, I would like to know:* how is a string value exactly implicitly converted?* how exactly does the estimation work, that in case of doubt rounds a value up or off?Thank You!
Post #1521173
 Posted Tuesday, December 10, 2013 10:43 PM
 Hall of Fame Group: General Forum Members Last Login: Wednesday, February 24, 2016 6:28 AM Points: 3,977, Visits: 6,431
 The last thing I want to try to do is explain the implicit conversion rules SQL chooses to use in these kinds of cases.Your best bet is to CAST the VARCHAR to a DECIMAL type explicitly and then do the rounding, so that there is no ambiguity with respect to what the result will be. My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!My thought question: Have you ever been told that your query runs too fast?My advice:INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.Need to UNPIVOT? Why not CROSS APPLY VALUES instead?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
Post #1521741
 Posted Wednesday, December 11, 2013 2:33 AM
 SSC-Enthusiastic Group: General Forum Members Last Login: Saturday, November 26, 2016 1:04 PM Points: 153, Visits: 398
 Thank you Dwain,yep, I hoped someone could explain the implicit conversion rules...
Post #1521784

 Permissions