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

C# Convert string with decimals to smallint

Options
  • 18-11-2010 4:35pm
    #1
    Registered Users Posts: 1,830 ✭✭✭


    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 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 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 Posts: 1,830 ✭✭✭CountingCrows


    Great stuff guys, thanks.


Advertisement