Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.format() not showing values

Tags:

c#

.net

Can anyone tell me why does this string.Format() doesn't show the 1st value?

long countLoop = 0;
long countTotal = 3721;

string.Format("Processed {0:#,###,###} lines of {1:#,###,###} ({2:P0})", countLoop, countTotal, ((double)countLoop / countTotal));

The result I got are

Processed  lines of 3,721 (0 %) 

But if I replaced countTotal with a number 1

string.Format("Processed {0:#,###,###} lines of {1:#,###,###} ({2:P0})", 1, countTotal, ((double)countLoop / countTotal));

I get this

Processed 1 lines of 3,721 (0 %).

Is there something about string.Format that I don't know about?

like image 204
fletchsod Avatar asked Mar 27 '26 16:03

fletchsod


1 Answers

See the documentation on the the "#" custom format specifier:

Note that this specifier never displays a zero that is not a significant digit, even if zero is the only digit in the string.

If you'd like to display "0" in this case, take a look at the "0" custom format specifier:

If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string.

This should work for you:

string.Format(
    "Processed {0:#,###,##0} lines of {1:#,###,###} ({2:P0})", 
    countLoop, countTotal, ((double)countLoop / countTotal));
like image 141
p.s.w.g Avatar answered Mar 31 '26 09:03

p.s.w.g