Set default value to null when converting to double in c# - 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;

Related

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());
}

What is the difference between these 2 statements?

Possible Duplicate:
C# ?: Conditional Operator
statement first:
if(dr["AskingPriceFrom"]!=System.DBNull.Value)
objFilters.AskingPriceFrom=Convert.ToDecimal(dr["AskingPriceFrom"]);
else
objFilters.AskingPriceFrom=null;
statement second:
objFilters.AskingPriceFrom=Convert.ToDecimal(
dr["AskingPriceFrom"]!=System.DBNull.Value ? dr["AskingPriceFrom"] : null
);
What is difference between these two statements?
In first statement, if value is empty in if-else condition, then it stores null value correctly; but, if value is empty in the second condition, then instead of storing null value it stores 0. AskingPriceFrom is a get-set field stores decimal value. I tried to convert only dr["AskingPriceFrom"] after the question mark but the statement gives me an error.
Is there any way to protect null value from converting in decimal?
Apparently Convert.ToDecimal(null) == 0
//Edit: This should work
objFilters.AskingPriceFrom =
(dr["AskingPriceFrom"] != System.DBNull.Value) ?
Convert.ToDecimal(dr["AskingPriceFrom"]) : null;
It's because Decimal is not nullable. You should cast to decimal? so that when you convert a null to that type it will not return the default value 0 but instead return null.
in the inline version(ternary)
if it is null you will get:
objFilters.AskingPriceFrom = Convert.ToDecimal(null);
this will probably result an error.
You should read Convert.ToDecimal documentation here http://msdn.microsoft.com/en-us/library/e6440ed8.aspx.
Convert.ToDecimal returns decimal or throws exception, but in your case you need return type as Nullable<decimal>.
You can use code like this:
decimal? result;
if (Convert.IsDBNull(dr["AskingPriceFrom"]))
{
result= null;
}
else
{
result = dr.GetDecimal(reader.GetOrdinal("AskingPriceFrom"));
}
Thanks a lot to https://stackoverflow.com/users/1336654/jeppe-stig-nielsen. This is working properly.
objFilters.AskingPriceFrom = dr["AskingPriceFrom"] != System.DBNull.Value ? Convert.ToDecimal(dr["AskingPriceFrom"]) : (decimal?)null;

Why can't I assign null to decimal with ternary operator?

I can't understand why this won't work
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
? decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))
: null;
Because null is of type object (effectively untyped) and you need to assign it to a typed object.
This should work:
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
? decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))
: (decimal?)null;
or this is a bit better:
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
? decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))
: default(decimal?);
Here is the MSDN link for the default keyword.
Don't use decimal.Parse.
Convert.ToDecimal will return 0 if it is given a null string. decimal.Parse will throw an ArgumentNullException if the string you want to parse is null.
Try this:
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ?
decimal.Parse(txtLineCompRetAmt.Text.Replace(",", "")) :
(decimal?) null;
The problem is that the compiler does not know what type nullhas. So you can just cast it to decimal?
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ?
decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) :
(decimal?)null;
Because the compiler can't infer the best type from the operands of the conditional operator.
When you write condition ? a : b, there must be an implicit conversion from the type of a to the type of b, or from the type of b to the type of a. The compiler will then infer the type of the whole expression as the target type of this conversion. The fact that you assign it to a variable of type decimal? is never considered by the compiler. In your case, the types of a and b are decimal and some unknown reference or nullable type. The compiler can't guess what you mean, so you need to help it:
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
? decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))
: default(decimal?);
You need to cast the first part to decimal?
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
? (decimal?)decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))
: null;

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 can I convert decimal? to decimal

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.

Categories

Resources