Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string custom format to add trailing zeroes

Tags:

c#

formatting

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?

like image 607
jneko Avatar asked May 07 '26 15:05

jneko


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"
>
like image 133
Mario Welzig Avatar answered May 10 '26 04:05

Mario Welzig


This should work:

 decimal value = 10;
 var  str = string.Format("{0,8:###.0000}", value);
like image 27
mspaic96 Avatar answered May 10 '26 04:05

mspaic96



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!