Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explaining confusing conditional string format

An ex-coworker wrote this:

String.Format("{0:#;;} {1:records;no records;record}", rows, rows - 1);
//Rows is a integer value

I read articles like these

Code Project - Custom String Formatting in .NET
MSDN - Custom Numeric Format Strings

But I don't still get it how that format works. Obviously I can see the output but I don't understand this part {0:#;;} and the second one. I want to do the same thing for specifying ages (year, years...)

I'm very curious about this string format. Can someone can explain this behavior? The author does not work with us anymore.

like image 859
Maximus Decimus Avatar asked Sep 02 '14 16:09

Maximus Decimus


People also ask

What is the point of string formatting?

String formatting uses a process of string interpolation (variable substitution) to evaluate a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

What is string types of formatting of string?

A string format specifier “%” followed by a dedicated character for each data type is used for formatting the strings. As you see, the format specifier %s was used to format the string name and %d was used to format the integer num. Similarly, there is a format specifier for a float as well.

What does .format do in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.


1 Answers

This is a custom numeric format string, basically - but a pretty odd one, to be honest. In fact, it's two of them:

#;;
records;no records;record

In each case, you've got three sections, due to having two section separators (the semi-colons):

The first section applies to positive values, the second section applies to negative values, and the third section applies to zeros.

Your situation is further complicated by the developer using rows - 1 as the value to be formatted by the second format string, so it's really:

  • records if rows is greater than 1 (so rows - 1 is positive)
  • no records if rows is equal to 0 (so rows - 1 is negative)
  • record if rows is equal to 1 (so rows - 1 is zero)

And the first format string only includes the value of rows (due to the #) if rows is positive. So the overall result is:

Rows     Result
   2     2 records  (ditto for other values greater than 1)
   1     1 record
   0     no records

Personally I would have either used a conditional operator for that, or if/else statements - using a custom numeric format string is "clever" in the worst way...

like image 94
Jon Skeet Avatar answered Sep 22 '22 19:09

Jon Skeet