Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include If Else statement in String.Format

I have the following statemnt.

  timespan = timespan.FromSeconds(236541)
  formattedTimeSpan = String.Format("{0} hr {1} mm {2} sec", Math.Truncate(timespan.TotalHours), timespan.Minutes, timespan.Seconds)

I have to have it formatted as "hrs mn sec" if there are more than one hour. I want to check this within the String.Format above.

Thanks.

like image 900
Narazana Avatar asked Aug 18 '10 04:08

Narazana


People also ask

What is %s in string format?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.

How do you write in string format?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.

How do I format a string in C #?

Example 1: C# String Format()string strFormat = String. Format("There are {0} apples.", number);

How do you use conditionals F strings in Python?

Use a ternary operator to use f-strings for conditional formatting, e.g. result = f'{my_str. upper() if condition else my_str. lower()}' .


3 Answers

Probably the cleanest way to do this is to write your own ICustomFormatter. Here's an example of a convenient pluralizer format:

using System;

public class PluralFormatter : IFormatProvider, ICustomFormatter {

   public object GetFormat(Type formatType) {
      if (formatType == typeof(ICustomFormatter))
         return this;
      else
         return null;
   }

   public string Format(string format, object arg, 
                          IFormatProvider formatProvider)
   {   
      if (! formatProvider.Equals(this)) return null;

      if (! format.StartsWith("^")) return null;

      String[] parts = format.Split(new char[] {'^'});
      int choice = ((int) arg) == 1 ? 1 : 2;
      return String.Format("{0} {1}", arg, parts[choice]);
   }

   public static void Main() {
      Console.WriteLine(String.Format(
         new PluralFormatter(),
         "{0:^puppy^puppies}, {1:^child^children}, and {2:^kitten^kittens}", 
         13, 1, 42
      ));
   }
}

The output is, as one might've guessed (and as seen on ideone.com):

13 puppies, 1 child, and 42 kittens

MSDN links

  • Custom Formatting with ICustomFormatter
  • System.ICustomFormatter
  • System.IFormatProvider
like image 104
polygenelubricants Avatar answered Oct 27 '22 22:10

polygenelubricants


One possibility is to make the plural part of the format string, and write:

formattedTimeSpan = String.Format("{0} hr{1} {2} mm {3} sec",
    Math.Truncate(timespan.TotalHours),
    Math.Truncate(timespan.TotalHours) == 1 ? "" : "s",
    timespan.Minutes,
    timespan.Seconds);

This will insert a "s" into the output if the output says anything other than "1 hr".

Note that this is not friendly to localization: other languages form plurals differently than English.

like image 33
Bradley Grainger Avatar answered Oct 27 '22 23:10

Bradley Grainger


No magic here. Why would you code in whatever condition format may offer, when you can code in C#?

To avoid duplicated code, you might as promote some expressions to variables, and use the condition on them:

timespan = timespan.FromSeconds(236541);
int hours = Math.Truncate(timespan.TotalHours);
string hoursUnit = hours == 1 ? "hr" : "hrs";
formattedTimeSpan = String.Format("{0}{1} {2} mm {3} sec",
                        hours, hoursUnit, timespan.Minutes, timespan.Seconds);
like image 3
Kobi Avatar answered Oct 28 '22 00:10

Kobi