• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 455
  • Last Modified:

C# - String.Format - String replace question

Hello all,

Think this should be rather simple but not sure easiest way.  I have the following:

String.Format("{0:N2} %", Model.Yield)

If Model.Yield is null I don't want to show the "%" sign.   Right now if the value Model.Yield is null it shows just the percent sign and I want it to be blank.

1 Solution
So why not use:

if Model.Yield is null
String.Format("{0:N2} %", Model.Yield)
String.Format("{0:N2} ", Model.Yield)

Open in new window

Kyle AbrahamsSenior .Net DeveloperCommented:
String.Format("{0:N2}{1}", Model.Yield, Model.Yield == null ? "" : " %")
Miguel OzSoftware EngineerCommented:
A bit simpler version of the above:
Model.Yield == null ? String.Empty : String.Format("{0:N2} %", Model.Yield)
sbornstein2Author Commented:
This was the cleanest way I used actually.   Thanks all
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now