Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal.ToString not working if the value is zero

Tags:

c#

linq

sum

I have following code-

Label1..Text = dt.AsEnumerable().Sum(x => x.Field<decimal?>("col1") ?? 0).ToString("#,#.####", CultureInfo.InvariantCulture);

here, I am displaying the sum of 'col1' onto a label.
I am checking x.Field<decimal?>("col1") for null values

the problem is, if the value of a column is something like 1234, it displays properly, but if x.Field<decimal?>("col1") is null then it takes the value as ZERO and nothing displays on the label.

It seems like toString ignores the value if it is zero and returns nothing.

Please help

like image 219
Microsoft DN Avatar asked Jan 11 '23 00:01

Microsoft DN


1 Answers

Use format "#,0.####" That will show 0 for 0 values and 1,234 for 1234

Label1.Text = dt.AsEnumerable()
                 .Sum(x => x.Field<decimal?>("col1") ?? 0)
                 .ToString("#,0.####", CultureInfo.InvariantCulture);

You should see: Custom Numeric Format Strings.

"0" - Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

like image 182
Habib Avatar answered Jan 21 '23 06:01

Habib