Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

C# Convert string with decimals to smallint

  • 18-11-2010 03:35PM
    #1
    Registered Users, Registered Users 2 Posts: 1,835 ✭✭✭


    Problem:

    I'm reading in information from one table and adding it to another via a SQL statement. All the fields are being imported as string. So I've values such as "200.000" which I need to add to a smallint SQL column (e.g format to "200").

    Lines below fail;
    string sValue = "200.000"
    int iValue;
    
    iValue = System.Convert.ToInt16(sValue)
    iValue = Int16.Parse(sValue)
    

    Any ideas?


Comments

  • Registered Users, Registered Users 2 Posts: 515 ✭✭✭NeverSayDie


    Well, you could just parse it as it is, a decimal, and then downcast that to an int. Obviously you're liable to lose information there, but presumably that's part of your spec. Watch out for overflows/underflows too. Alternatively, you could process the string beforehand to trim off any decimals - see regular expressions Replace() method for instance.


  • Registered Users, Registered Users 2 Posts: 7,182 ✭✭✭Genghiz Cohen


    String sValue = "200.900";
    int iValue = (int)Convert.ToDecimal(sValue);
    

    Outputs 200 to the console.


  • Closed Accounts Posts: 10,012 ✭✭✭✭thebman


    I recommend using regular expressions. Look into expresso, a gui tool for aiding you in creating reg expressions and its free.

    It will even generate the C# code for you.

    http://www.ultrapico.com/Expresso.htm

    Its a good way to test your reg expressions before putting them into your code with sample data too. Legend of a program.


  • Registered Users, Registered Users 2 Posts: 1,835 ✭✭✭CountingCrows


    Great stuff guys, thanks.


Advertisement