Samantha J T Star
Samantha J T Star

Reputation: 32758

How can I parse a value to show as an integer in a razor view?

I have

    @{
    var to = Model.PageMeta.TestID == "00" ? "All Tests" : Model.PageMeta.TestID;
    }

The value of TestID can be "00","01","02" etc

What I would like to do is display this as "All Tests", "1", "2" etc. In other words I want to just show the value without the leading zero.

I tried

parseInt(Model.PageMeta.TestID) 

but this gave me a compiler error.

Upvotes: 1

Views: 19164

Answers (4)

Mihalis Bagos
Mihalis Bagos

Reputation: 2510

Actually the simplest but most complete would be this:

 @{
 var to = Model.PageMeta.TestID == "00" ? 
  "All Tests" : 
         (Model.PageMeta.TestID.StartsWith("0") ? 
                 Model.PageMeta.TestID.Substring(1) : 
                 Model.PageMeta.TestID);
  }

Upvotes: 0

John
John

Reputation: 6553

If its a string, use Convert.ToInt32()

using System;

public class Test
{
    public static void Main()
    {
            string s = "00";
            string s2 = "04";

            int i = Convert.ToInt32(s);
            int i2 = Convert.ToInt32(s2);

            Console.WriteLine("{0}|{1}", i, i2);
    }
}

Output:

0|4

Compared to TrimStart:

using System;

public class Test
{
    public static void Main()
    {
            string s = "00";
            string s2 = "04";

            Console.WriteLine("{0}|{1}", s.TrimStart('0'), s2.TrimStart('0'));
    }
}

Output:

|4

Upvotes: 0

Ian Mercer
Ian Mercer

Reputation: 39277

The easiest way to do that would be to use TrimStart

Upvotes: 2

marcind
marcind

Reputation: 53183

Try the Int32.Parse() method.

Upvotes: 5

Related Questions