webworm
webworm

Reputation: 11019

Cannot format nullable decimal using ToString("#.##")

How do I format a nullable decimal such that it's string output is formatted to two decimal places?

Salary = g.Where(x => !String.IsNullOrEmpty(x.Salary))
.Select(x => (decimal?)decimal.Parse(x.Salary))
.DefaultIfEmpty(null)
.Sum().ToString();

The above works but sometimes yields a decimal results that is very long

203827.82763651324038269

I would like to format the result to two decimal places

203827.83

Since my desired output is a string I thought I could just use

.Sum().ToString("#.##);

Bu t I get an error No overload for method 'ToString' takes 1 arguments which I think is due to the results being a nullable decimal. How do I work around this?

Upvotes: 1

Views: 1098

Answers (2)

DavidG
DavidG

Reputation: 119017

You are right, Nullable(T).ToString() doesn't take any arguments. Instead, you can use good old fashioned string.Format or the string interpolation shorthand:

var result = g.Where(x => !String.IsNullOrEmpty(x.Salary))
    .Select(x => (decimal?)decimal.Parse(x.Salary))
    .DefaultIfEmpty(null)
    .Sum();

Salary = $"{result:#.###}";

However, it's not clear why you are casting to decimal? here, why not simply this:

Salary = g.Where(x => !String.IsNullOrEmpty(x.Salary))
    .Select(x => decimal.Parse(x.Salary))
    .Sum()
    ToString("#.###");

Of course, I would suggest keeping the x.Salary values as decimal rather than string, but that's a different story.

Upvotes: 1

Obie
Obie

Reputation: 477

Yes, you're right. The nullable decimal's ToString doesn't take any parameters and has no overloads. You need to access the Value of the nullable decimal:

var Salary = g.Where(x => !String.IsNullOrEmpty(x.Salary))
.Select(x => (decimal?)decimal.Parse(x.Salary))
.DefaultIfEmpty(null)
.Sum();
var result=Salary.HasValue?Salary.Value.ToString("#:##"):"";

Upvotes: 1

Related Questions