Absolute of decimal nullable

  • Thread starter Thread starter Luigi Z
  • Start date Start date
L

Luigi Z

Hi all,
how can I get the absolute value of a decimal nullable value? (C# 2.0).

Thanks a lot.
 
Luigi Z said:
how can I get the absolute value of a decimal nullable value? (C# 2.0).

You can add to your code a function for this purpose:

public decimal? Abs(decimal? d)
{
if (d.HasValue && d.Value<0) return -d.Value;
return d;
}
 
Alberto Poblacion said:
You can add to your code a function for this purpose:

public decimal? Abs(decimal? d)
{
if (d.HasValue && d.Value<0) return -d.Value;
return d;
}

Good solution, thank you Alberto.

Luigi
 
Hi Alberto,
a little similar question.
How can I round a decimal nullable, like in this snippet:

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

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

The problem is to round "value" in totalValue += value;
Have you idea?

Thanks a lot

Luigi
 
Luigi Z said:
[...]
foreach (decimal? value in valuesList)
[...]
totalValue += value;
[...]
The problem is to round "value" in totalValue += value;
Have you idea?

Simply get the Value of value (if it HasValue) and apply whatever
rounding formula you desire to this (non-nullable) decimal.

For instance:

private decimal MyRound(decimal? v)
{
if (v.HasValue)
{
decimal d = v.Value;
return decimal.Round(d,0);
}
return 0;
}

Now do:
totalValue += MyRound(value);
 
Back
Top