1

I am using string.format to format my model value inside razor view but it does not gives desired result

@string.Format("{0:00}", Model.Range == null ? "" : Model.Range.ToString())

It should result as 05

if i am using below it gives me result but not from model

@string.Format("{0:00}", 5)

Someone have any idea or same experience ?

3
  • Try removing {0:00} with {0} Commented Apr 30, 2013 at 14:32
  • 1
    What type of "Range" ? Commented Apr 30, 2013 at 14:34
  • This is only a property of model. Commented Apr 30, 2013 at 15:34

1 Answer 1

5

If Model.Range is a number type then you need to write:

@string.Format("{0:00}", Model.Range == null ? "" : Model.Range)

because with the Model.Range.ToString() you have converted your Range to string so the number formatting cannot be applied because it is not a number anymore.

By the way string.Format handles null arguments so it is enough to write:

@string.Format("{0:00}", Model.Range)

If Model.Range is not a number but with Model.Range.ToString() you get a number in a string representation then you need to first convert it to a number (like using int.Parse or its other variants) then you can pass the number to string.Format which can now apply the correct formatting.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks namesv this is exact explanation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.