jneko
jneko

Reputation: 143

C# string custom format to add trailing zeroes

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?

Upvotes: 3

Views: 902

Answers (2)

mspaic96
mspaic96

Reputation: 91

This should work:

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

Upvotes: 1

Mario Welzig
Mario Welzig

Reputation: 618

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"
>

Upvotes: 5

Related Questions