C# string custom format to add trailing zeroes

Viewed 198

I'm trying to convert a decimal to a string with 8 characters. It should have a leading white space if there are less than 3 digits before the decimal and always have four digits. Below is what I've tried and the results I've gotten.

decimal value=1; // What I want "  1.0000"
string str = value.tostring("###.0000"); // str ends up being "1"
str = string.Format("{0:###.0000}",1); // str ends up being "1.0000"
str = string.Format("{0,8}:###.0000",value); // str ends up being "       1"

What am I doing wrong?

2 Answers

The idea behind your third format specifier is correct, but the syntax isn't.
This works:

> string.Format("{0,8:###.0000}", 1M)
"  1.0000"
>

Alternate version using string interpolation:

> decimal value = 1M;
> $"{value,8:###.0000}"
"  1.0000"
>

This should work:

 decimal value = 10;
 var  str = string.Format("{0,8:###.0000}", value);
Related