can someone give me tips on how to use the cast function to display words?

  • Im having a problem I have to use the cast function to display my freight amount for instance if the freight amount is 65.83 I need to display (the freight cost is 65 dollars and 83 cents) I have no idea how to display words any tips would be appreciated thanks.

  • CAST is not needed. At least for what you posted.

    SELECT *,

    'the freight cost is ' + REPLACE(cost, '.', ' dollars and ') + ' cents'

    FROM (VALUES(65.83)) x(cost)

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • Nice one Luis. I would have thought SQL would try and make everything numeric.

  • The magic is in the REPLACE() which will implicitly convert the number into a string when it receives the data. Other string functions such as LEFT(), RIGHT(), LEN() and others would do the same. Some like SUBSTRING() will fail.

    And to expand a little bit, when you try to concatenate a number to a string, you need to convert (either implicitly or explicitly) the number into a string or SQL Server will try to convert the string into a number and add it. To know how implicit conversions will work and avoid surprises, use the following reference: https://msdn.microsoft.com/en-us/library/ms190309.aspx

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • i will certainly check that out but the requirement was to experiment with the cast function so i will keep trying thankyou

  • Luis Cazares (4/13/2015)


    CAST is not needed. At least for what you posted.

    SELECT *,

    'the freight cost is ' + REPLACE(CAST(cost AS VARCHAR(20)), '.', ' dollars and ') + ' cents'

    FROM (VALUES(65.83)) x(cost)

    You can try it this way:-D

  • karodhill (4/14/2015)


    i will certainly check that out but the requirement was to experiment with the cast function so i will keep trying thankyou

    CAST is very simple :-). You'll have more fun with CONVERT and the format codes.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • I appreciate the effort you took to show me examples The last one worked for me thanks so much

Viewing 8 posts - 1 through 7 (of 7 total)

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