differences in rounding / converting strings

  • 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

    with

    It'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.28

    SELECT ROUND(0.285,2) -- 0.29

    SELECT 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 estimate

    But 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!

  • 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![/I]

    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?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • Thank you Dwain,

    yep, I hoped someone could explain the implicit conversion rules...

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply