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());
}
Related
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;
I have the following code -
int lat = System.Convert.ToInt16(latTextBox1.Text);
This is happening on a changed event.
However my code is breaking on this line saying -
Input string was not in a correct format.
Where latTextBox1.Text = "" which is an empty string.
I think this is breaking because it cannot convert an empty string into a null value.
How can I modify my code to account for null values?
OK, based on your comment you could use:
int? lat = string.IsNullOrEmpty(latTextBox1.Text)
? (int?)null : Convert.ToInt32(latTextBox1.Text);
int? is a nullable int.
How about a simple:
int? lat = null;
int dummyLat;
if (Int32.TryParse(latTextBox1.Text, out dummyLat)
lat = dummyLat;
On a side note:
I' never convert strings in the TextChanged event ever! Why? Because it triggers an event upon every keypress! Use some other trigger to initiated the conversion (for example a button).
Well, Convert.ToInt16 isn't meant to convert an empty string into a null value... indeed it can't, given that the return type is a non-nullable Int16 (aka short).
I suspect you actually want something more like:
int lat;
if (int.TryParse(latTextBox1.Text, out lat))
{
// Use lat
}
else
{
// Invalid or empty input. Handle appropriately.
}
If you want to handle empty strings differently to invalid input, you'll need to do that explicitly - although you should also consider whether "just whitespace" is equivalent to "empty" or "invalid".
You could use the following method:
Int16.TryParse:
Or you could check if the string is not null or empty before performing the logic:
if (!string.IsNullOrEmpty(latTextBox1.Text)) {
lat = System.Convert.ToInt16(latTextBox1.Text);
}
http://msdn.microsoft.com/en-us/library/system.int16.tryparse.aspx
you should first check that the current value is not an empty one before trying to convert it to an integer, kindly check out the following snippet
int lat = 0;
If(! string.IsNullorEmpty(latTextBox1.Text))
{
lat = System.Convert.ToInt32(latTextBox1.Text);
}
// use your lat variable here
Update:
From your comment above, lat may hold the NULL value, so you will have to make it a nullable Int in order to make it hold the value NULL
consider this updated code snippet
int? lat = 0;
If(! string.IsNullorEmpty(latTextBox1.Text))
{
lat.value = System.Convert.ToInt32(latTextBox1.Text);
}
// use your lat variable here by accessing the lat.value property
Note: latiture and longtitude values should be stored in a double datatype in order to preserve the precision.
You have to check for the string being set:
int lat = 0;
if (string.IsNullOrEmpty(latTextBox1.Text)
{
// Your null case here
}
else
{
lat = System.Convert.ToInt16(latTextBox1.Text);
}
Though:
int lat = 0;
if (!Int32.TryParse(latTextBox1.Text, out lat)
{
// Error handling here
}
is probably a better approach as it copes with non numeric input.
int lat = 0;
if (Int32.TryParse(laTextBox1.Text, out lat))
{
//success, textbox contained an int, now lat has the value of that int
}
else
{
//failure, textbox did not contain an int
}
int i = 0;
if (!Int32.TryParse(latTextBox1.Text, out i)) {
i = 0; // or default value;
}
One liner:
int lat = System.Convert.ToInt16(latTextBox1.Text.Length == 0 ? 0 : latTextBox1.Text);
Basically works like coalesce, if latTextBox1.Text does not have a value, set it to zero
otherwise the value from latTextBox1.Text
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.
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;
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.