C# - Convert String/Null to decimal [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a method and argument as a string or null. So I am trying to convert the arguments into decimal.. I am trying to use decimal.Parse to convert string to decimal.
If the argument has a null value don't want to convert as a decimal..
public void abcd(string price)
{
decimal result = string.IsNullOrEmpty(price) ? null : decimal.Parse(price);
//error - cannot convert null as decimal
//I tried few other options also.
decimal result = price is null ? 0 : decimal.Parse(price);
// error - VAlue cannot be null
//have other logic here
}
abcd("123");
abcd(null);

If you want a null to represent the absence of value, you can use a nullable variable:
decimal? result = string.IsNullOrEmpty(price) ? null : decimal.Parse(price);
This is a better option than representing a lack of data by a zero as proposed by others.
You may have to check if result is null before using it for certain purposes. However, the usual operations are supported:
See Math operations with null

string i = null;
decimal result;
decimal.TryParse(i, out result);
Console.WriteLine(result.ToString()); // 0

You can set 0 when the string is null or empty.
Please follow the below answer.
public void abcd(string price)
{
decimal result = string.IsNullOrEmpty(price) ? 0: decimal.Parse(price);
}

Try -
public static void abcd(string price)
{
decimal result = string.IsNullOrEmpty(price) ? 0 : decimal.Parse(price);
decimal result2 = price is null ? 0 : decimal.Parse(price);
//have other logic here
}

Related

cannot convert from 'double' to 'System.ReadOnlySpan<char>' error when trying to use `TryParse` [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm currently learning C# and I'm having troubles. I'm getting cannot convert from 'double' to 'System.ReadOnlySpan<char>' error when I try to use !double.TryParse
static double userDouble, correctDouble;
static void someMethod() {
Console.Write(someStringOfDoubles);
while(!double.TryParse(userDouble, out _)) {
try {
userDouble= Double.Parse(Console.ReadLine());
}
catch {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
}
// checks if the userDouble is correct or not.
if (Math.Round(correctDouble, 2) == userDouble) {
Console.WriteLine("You are Correct!\n");
}
else {
Console.WriteLine("You are Incorrect.");
}
}
What should it do: Check if userDouble is a valid double and not letter(s)/word(s).
I also tried:
while(!double.TryParse(Console.ReadLine(), out userDouble)) {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
but this gives me No overload for method 'TryParse' takes 1 arguments
Any help would be much appreciated!
You need to get console value in string variable first then check it with double.TryParse(...). Try like below.
string s = Console.ReadLine();
while(!double.TryParse(s, out userDouble)) {
Console.WriteLine($"{s} is an invalid input\n\n");
s = Console.ReadLine();
}
Below attempt of yours must work without any error. But only problem you will face is it will write 0 is an invalid input for evert input because double.TryParse will set userDouble = 0 when value from Console.ReadLine() are not double.
while(!double.TryParse(Console.ReadLine(), out userDouble)) {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}

Convert a string to Double in C# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I just wrote a method to convert a string to double. It does what it's suppose to do, but it seems too long and I'm thinking there's a better way of writing it. Please review and suggest a better way or point out why this is not good for production code.
static double ConvertStringToDouble(string input, int rounding)
{
string[] split = input.Split('.');
double wholeNumber = 0.0;
if (split.Length > 0 && Int32.TryParse(split[0], out int temp))
wholeNumber = (double)temp;
double decimalNumber = 0.0;
if (split.Length > 1)
{
string decimalString = (split[1].Length < rounding) ? split[1] : split[1].Substring(0, rounding);
if (Int32.TryParse(decimalString, out int dec))
decimalNumber = (double)dec / Math.Pow(10, decimalString.Length);
}
return wholeNumber + decimalNumber;
}
This is the updated method now. Thanks all for the contributions
static double ConvertStringToDouble(string input, int rounding)
{
if (double.TryParse(input, out double value))
return Math.Round(value, rounding);
else return 0.0;
}
.Net has built in functionality for this, its called Double.TryParse. Double.Parse also exists, but its recommended to use the Try variant, as it won't throw exceptions if the number is not parseable into a double. You can use the method like this
string stringToParse = "1.7346"
if (Double.TryParse(stringToParse, out double parsedDouble))
{
//do something with the double here
}
else
{
//failed to parse, error logic here
}
You can just use double.Parse and double.TryParse methods, I prefer to use them like this:
string myString = "1.05";
// This throws exception:
double myParsedDouble = double.Parse(myString);
// This gives you more control over the conversion:
double? myResult = null;
if (double.TryParse(myString, out double _myResult))
myResult = _myResult;
if (myResult == null)
{
throw new ArgumentException("Not a valid double!");
}

CS0030: Cannot convert type 'int' to 'bool' [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
where is the problem with my code??
i can't compile it on microsoft visual studio 2015
anyone can help? what should i change and where is the problem?
private void SelectAll_ItemClick(object sender, ItemClickEventArgs e)
{
GridColumn column = (GridColumn) e.Item.Tag;
int dataRowCount = this.gridViewCastles.DataRowCount;
bool flag1 = true;
bool flag2 = true;
this.gridViewCastles.BeginUpdate();
try
{
for (int rowHandle = dataRowCount - 1; rowHandle >= 0; --rowHandle)
{
if (flag1)
{
flag2 = !(bool) this.gridViewCastles.GetRowCellValue(rowHandle, column);
flag1 = false;
}
this.gridViewCastles.SetRowCellValue(rowHandle, column, (object) (bool) (flag2 ? 1 : 0));
}
}
finally
{
this.gridViewCastles.EndUpdate();
}
}
The problem is here: (bool) (flag2 ? 1 : 0). You're trying to convert an integer to a boolean using an explicit cast.
Use Convert.ToBoolean instead: Convert.ToBoolean(flag2 ? 1 : 0). BTW, it seems like it's so useless: why do you want to convert 1 to true and 0 to false if flag2 is already bool?
BTW, now you should have already realized that bool has no implicit or explicit conversion to int and vice versa and you need to use Convert.ToBoolean/Convert.ToInt32...
Replace:
this.gridViewCastles.SetRowCellValue(rowHandle, column, (object)(flag2);
By:
this.gridViewCastles.SetRowCellValue(rowHandle, column, (object)(bool)(flag2 ? 1 : 0));
this.gridViewCastles.SetRowCellValue(rowHandle, column, (object) (bool) (flag2 ? 1 : 0));
What are you trying to do?
Flag2 is a boolean. The ?: operator allows you to test a boolean condition to select one of two possible vaules, in your case, 0 and 1. In your code, you try to cast 0/1 to boolean. What is the reason for using the ?: operator? Just type this:
this.gridViewCastles.SetRowCellValue(rowHandle, column, (object) flag2);

Checking if json key exists for a given array index? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
This code throws an exception if the key does not exist.
For example, if the key exists for a position in an array index the code is okay, even if the value is null. But, if the key does not exist the code throws an exception`. The code in the select token parenthesis is dynamic (a string variable).
r["Value"] = json.SelectToken($.Objectives[x].state).ToString() ?? "";
You can't call ToString() on a null value.
JToken value = json.SelectToken("$.Objectives[x].state");
r["Value"] = (value != null) ? value.ToString() : "";
You could use the tenary operator to return a default value if x doesn't exist
r["Value"] = $.Objectives[x] ?
json.SelectToken($.Objectives[x].state).ToString() ?? "
: '';
OR
r["Value"] = x >= $.Objectives.Length ?
json.SelectToken($.Objectives[x].state).ToString() ?? "
: '';
I'm not sure why you end the line with a double quote. Maybe a typo? But I didn't fix it, that code is what you started with.
In javascript, if a given variable has a value, it will return true to the following:
if(r["Value"]){
//this only runs if r["Value"] exists
}

Optimize parsing more and more.... in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have below C# code for parsing ... Do you think this is most optimize or I should use generic method or optimization required in these function itself?
public static bool GetDBBool(object value)
{
var result = false;
if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
bool.TryParse(value.ToString(), out result);
return result;
}
public static int GetDBInt(object value)
{
var result = -999;
if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
int.TryParse(value.ToString(), out result);
return result;
}
public static double GetDBDouble(object value)
{
var result = -999.00;
if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
double.TryParse(value.ToString(), out result);
return result;
}
public static DateTime GetDBDate(object value)
{
var result = DateTime.Now;
if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
DateTime.TryParse(value.ToString(), out result);
return result;
}
public static DateTime? GetDBNullableDate(object value)
{
DateTime date;
if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
return DateTime.TryParse(value.ToString(), out date) ? date : (DateTime?)null;
else
return null;
}
There's nothing more you can optimize there. And I doubt that THIS is the slowest place in your program.
However your null-values are a bit odd. -999 for numbers? DateTime.Now for a DateTime? Are you sure that won't cause problems in other code? Those are pretty normal values which means that other code won't be able to distinguish whether you had a null, or an actual value. And this default value might be wrong for the other code.
If it was me, I'd use 0 for integer, and DateTime.MinValue for DateTime. Or better yet - just stick to nullables all the way.
"== false" is not very readable. Use ! instead.
If the "object value" is already of desired type (e.g. DateTime), it would be slower to convert it to string and then back again.
I would write instead
if (value is DateTime) return (DateTime)value;
I would not use var result = -999; as a return value.
If the conversion fails, you can either return Int32.MinValue (better than -999) or rather null.
Maybe also you would like to check for DBNull.Value? So first I would check for null and DBNull.Value, then "value is DateTime" check and the last thing would be DateTime.TryParse.

Categories