Round a decimal nullable

L

Luigi Z

Hi all,
I have a problem with this snippet:

decimal? totalValue = null;

foreach (decimal? value in valuesList)
{
if (!value.HasValue)
continue;

totalValue = totalValue ?? 0;
totalValue += value;
}

I need to Round with zero decimals the totalValue (of Decimal? type).

How can I solve?

Thank in advance.
 
G

Göran Andersson

Luigi said:
Hi all,
I have a problem with this snippet:

decimal? totalValue = null;

foreach (decimal? value in valuesList)
{
if (!value.HasValue)
continue;

totalValue = totalValue ?? 0;
totalValue += value;
}

I need to Round with zero decimals the totalValue (of Decimal? type).

How can I solve?

Thank in advance.

Use the Decimal.Round method.

I think that the code is cleaner this way:

decimal? totalValue = null;
foreach (decimal? value in valuesList) {
if (value.HasValue) {
totalValue = (totalValue ?? 0) + value.Value;
}
}
if (totalValue.HasValue) {
totalValue = Decimal.Round(totalValue.Value);
}

Instead of (totalValue ?? 0) you can also use
totalValue.GetValueOrDefaul(0).
 
L

Luigi Z

Göran Andersson said:
Use the Decimal.Round method.

I think that the code is cleaner this way:

decimal? totalValue = null;
foreach (decimal? value in valuesList) {
if (value.HasValue) {
totalValue = (totalValue ?? 0) + value.Value;
}
}
if (totalValue.HasValue) {
totalValue = Decimal.Round(totalValue.Value);
}

Perfect, thank you very much Goran.
Instead of (totalValue ?? 0) you can also use
totalValue.GetValueOrDefaul(0).

This is available in C# 3.0?
Unfortunately I must use C# 2.0.

Luigi
 
G

Göran Andersson

Luigi said:
Perfect, thank you very much Goran.


This is available in C# 3.0?
Unfortunately I must use C# 2.0.

Luigi

No, it's available in framework 2.0.

(Note my typo; it's GetValueOrDefault, not GetValueOrDefaul.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top