Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
if write convert.ToInt32() then it doesnot convert "" to 0 and also it does not convert 1.00 to 1. it only converts only integer format strings to int32.
if i use int.tryparse
it checkes if string is "" then assigns to 0 to varable but
i miss 1.00 as its not converted to 1

any help is appriciated thank you.
Posted
Comments
CHill60 2-Feb-15 8:14am    
What are you actually trying to do? You might need to manipulate or validate the strings before you get to this point.
varun150 3-Feb-15 1:29am    
i wanted to pass a integer variable to database.

Well yes - it's an integer converter, so a floating point value is not valid: it only parses valid integer strings!

I would use int.TryParse first, and if that failed, try again with double.TryParse. If that succeeds, then cast the value to an int (assuming it fits) and continue.
If that fails, then report an error or use your default.
 
Share this answer
 
Comments
varun150 3-Feb-15 0:05am    
thanks for your response! griff i thought there would be something like val() in vb.net thats why asked this question.
in vb.net all i did is use val() function it returns integer from string.
Try TryParse[^] for different types, like this:
C#
using System;

public class Program
{
    public static void Main()
    {
        string[] numberString = {"", "1", "1.00"}

        ;
        int intNumber;
        decimal decimalNumber;
        for (int i = 0; i < numberString.Length; i++)
        {
            if (Int32.TryParse(numberString[i], out intNumber))
            {
                Console.WriteLine(intNumber);
            }
            else if (Decimal.TryParse(numberString[i], out decimalNumber))
            {
                Console.WriteLine(decimalNumber);
            }
            else
            {
                Console.WriteLine("Conversion failed!");
            }
        }
    }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900