简体   繁体   中英

Create variable just a number from text/number string - Razor CSHTML

I have a variable var1 . In the current context, it is pulled from the database and will be one of those values:

2, 6, 7 6t, 7q, 8q,

The number will only ever be single digit.

The number will only ever be the first characters in the variable.

I would like to create a single character variable (the number) from the variable I have put in.

Here for instance my variable Fac1Raw has the value of 3c and I have tried to use this code:

var Fac1 = (int)(Fac1Raw.ToString().Substring(0, 1));

However I can't get it to work. Any ideas?

You can't convert String to integer type directly. For this, you have the Parse methods. If you know for sure the string won't be empty and first character is a digit, you can parse without catching errors:

var Fac1 = Int32.Parse(Fac1Raw.ToString().Substring(0, 1));

If you do want some validations to prevent your code from crashing:

string rawFac1 = Fac1Raw.ToString();
if (rawFac1.Length == 0 || !char.IsDigit(rawFac1[0]))
{
    //handle invalid value
}
else
{
    var Fac1 = Int32.Parse(rawFac1[0].ToString());
    //...rest of code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM