How can I convert decimal? to decimal - c#

may be it is a simple question but I'm try all of conversion method! and it still has error!
would you help me?
decimal? (nullable decimal) to decimal

There's plenty of options...
decimal? x = ...
decimal a = (decimal)x; // works; throws if x was null
decimal b = x ?? 123M; // works; defaults to 123M if x was null
decimal c = x.Value; // works; throws if x was null
decimal d = x.GetValueOrDefault(); // works; defaults to 0M if x was null
decimal e = x.GetValueOrDefault(123M); // works; defaults to 123M if x was null
object o = x; // this is not the ideal usage!
decimal f = (decimal)o; // works; throws if x was null; boxes otherwise

Try using the ?? operator:
decimal? value=12;
decimal value2=value??0;
0 is the value you want when the decimal? is null.

You don't need to convert a nullable type to obtain its value.
You simply take advantage of the HasValue and Value properties exposed by Nullable<T>.
For example:
Decimal? largeValue = 5830.25M;
if (largeValue.HasValue)
{
Console.WriteLine("The value of largeNumber is {0:C}.", largeValue.Value);
}
else
{
Console.WriteLine("The value of largeNumber is not defined.");
}
Alternatively, you can use the null coalescing operator in C# 2.0 or later as a shortcut.

It depends what you want to do if the decimal? is null, since a decimal can't be null. If you want to default that to 0, you can use this code (using the null coalescing operator):
decimal? nullabledecimal = 12;
decimal myDecimal = nullabledecimal ?? 0;

You can use.
decimal? v = 2;
decimal v2 = Convert.ToDecimal(v);
If the value is null (v), it will be converted to 0.

Related

Set default value to null when converting to double in c#

I want to pass the null if the string is empty while converting from string to double. Can somebody help me with the syntax? As where I going wrong?
Current Syntax:
IngredientMinRange = !string.IsNullOrEmpty(MinRange) ? Convert.ToDouble(MinRange) : null
A double cannot be null since it's a value- and not a reference type. You could use a Nullable<double> instead:
double? ingredientMinRange = null;
if(!string.IsNullOrEmpty(MinRange))
ingredientMinRange = Convert.ToDouble(MinRange);
If you later want the double value you can use the HasValue and Value properties:
if(ingredientMinRange.HasValue)
{
double value = ingredientMinRange.Value;
}
Using Nullable Types (C# Programming Guide)
If IngredientMinRange is already a Double?-property as commented you can assign the value either via if(as shown above) or in in one line, but then you have to cast the null:
IngredientMinRange = string.IsNullOrEmpty(MinRange) ? (double?)null : Convert.ToDouble(MinRange);
to assign null to a double you have to use Nullable<double> or double?. Assign it with this method here:
decimal temp;
decimal? IngredientMinRange = decimal.TryParse(MinRange, out temp) ? temp : (decimal?)null;
then you can continue working with IngredientMinRange. You get the value with IngredientMinRange.Value or check if it's null with IngredientMinRange.HasValue
If it MinRange is an object:
IngredientMinRange = !string.IsNullOrEmpty(MinRange.ToString()) ? Convert.ToDouble(MinRange) : 0;

How to test for null of Double variable

I am accessing an endpoint and getting JSON back. I loop through the object and I put the value in a double field. Sometimes the filed will be null. How do I handle the null case. Currently my code looks like:
double scanning_risk = double.Parse(JSONrecord[i].scanning_risk.ToString());
Just FYI. I was able to handle null errors with INT variables using the GetValueOrDefault() function like:
int Firm_Id = JSONrecord[i].Firm_Id.GetValueOrDefault();
Here is how I am handling strings:
string Deleted_At = JSONrecord[i].Deleted_At == null
? ""
: JSONrecord[i].Deleted_At.ToString();**
Is there a similar GetValueOrDefault() function for double or a similar way to handle the case when a double filed is null?
Thank you!
It should work the same as for ints:
double scanning_risk = JSONrecord[i].scanning_risk.DefaultOrEmpty();
Assuming, of course, that scanning_risk is a Nullable<double> field.
This code will return to you value or default value (0) for double:
double scanning_risk = 0;
double.TryParse(JSONrecord[i].scanning_risk.ToString(), out scaning_risk);
If you can have null in JSONrecord[i].scanning_risk use:
double scanning_risk = 0;
double.TryPerse(JSONrecord[i].scanning_risk == null ? "" : JSONrecord[i].scanning_risk.ToString(), out scanning_risk);
Also this method returns right default(0) value for double if string contains non numeric value.
Thanks eveyone.
This is what I ended up using:
double spread_charge = row.spread_charge == null
? 0
: double.Parse(row.spread_charge.ToString());
where my json class has double? spread_charge
double scanning_risk = 0;
if(!string.IsNullOrWhitespace(JSONrecord[i].scanning_risk.ToString())) {
scanning_risk = double.Parse(JSONrecord[i].scanning_risk.ToString());
}

Built in CastOrDefault?

I get the feeling there is something built in for this. If object is null i'd like the default value (or specifically 0 and I am only using decimal/int). Is there a built in way to write this function?
static int GetDecimalFromObject(object o){
return o==null?0:(decimal)o;
}
Convert.ToDecimal and Convert.ToInt32 will return zero if passed null.
Try to use Convert.ToDecimal()
A decimal number that is equivalent to value, or 0 (zero) if value is
null.
Try like this;
static decimal GetDecimalFromObject(object o)
{
return o == null ? Convert.ToDecimal(0) : Convert.ToDecimal(o);
}
or more efficient;
static decimal GetDecimalFromObject(object o)
{
return Convert.ToDecimal(o);
}
Firstly, the decimal and int data types can't be null, so they would be 0 by default.
If you have a nullable decimal (decimal?) use the HasValue method to check if it is null then assign your default of 0.
The ?? Operator might help, but you have to provide the default value:
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
Just to offer a different solution:
static int GetDecimalFromObject(object o)
{
return o as int? ?? 0;
}
Generic version:
static T GetValueFromObject<T>(object o) where T : struct
{
return o as T? ?? default(T);
}
Note that I've used the as operator. If you prefer to throw an exception in case o is not of the right type, use the cast operator.

How can I round a C# double nullable type?

I want to round a double? value so that if its value is 2.3 the result should be 2 but if the input is null then the result should be null.
There is no direct way to round a nullable double. You need to check if the variable has a value: if yes, round it; otherwise, return null.
You need to cast a bit if you do this using the conditional ?: operator:
double? result = myNullableDouble.HasValue
? (double?)Math.Round(myNullableDouble.Value)
: null;
Alternatively:
double? result = null;
if (myNullableDouble.HasValue)
{
result = Math.Round(myNullableDouble.Value);
}
As others have pointed out, it is easy enough to do this as a one-off. To do it in general:
static Func<T?, T?> LiftToNullable<T>(Func<T, T> func) where T : struct
{
return n=> n == null ? (T?) null : (T?) func(n.Value);
}
And now you can say:
var NullableRound = LiftToNullable<double>(Math.Round);
double? d = NullableRound(null);
And hey, now you can do this with any method that takes and returns a value type.
return d.HasValue ? Math.Round(d.Value) : (double?)null;

How to check for valid value before converting Decimal

I assume this will blow up if total is null (I don't recall if decimals are initalized to null at the beginning or zero)
public int SomePropertyName
{
get { return Convert.ToInt32(Decimal.Round(total)); }
}
So should I check for null or > 0 ?
Decimal is a value type - there's no such value as "null" for a decimal.
However, it's perfectly possible for a decimal to be out of range for an int. You might want:
decimal rounded = decimal.Round(total);
if (rounded < int.MinValue || rounded > int.MaxValue)
{
// Do whatever you ought to here (it will depend on your application)
}
return (int) rounded;
I'm somewhat confused as to why you're using Convert.ToInt32 at all though, given that your property is declared to return a decimal. What's the bigger picture here? What are you trying to achieve?
Decimal is a value type and can not be null.
If you need to know if it had been initialized, you should probably use a nullable decimal:
Decimal? total = null;
public int SomePropertyName
{
get
{
if (total.HasValue) Convert.ToInt32(Decimal.Round(total.Value));
return 0; // or whatever
}
}
Decimals are value types, and so cannot be null.
So no need to check there..
As others have said, Decimal is a value type and cannot be null. However, if converting from a string then Decimal.TryParse is your friend...
System.Decimal is a value type, so it cannot be null. Second thing, the method's return value is decimal, so why would you want to convert to a Int32?

Categories

Resources