Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

C# Convert string with decimals to smallint

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


    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,007 ✭✭✭✭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,841 ✭✭✭CountingCrows


    Great stuff guys, thanks.


Advertisement