Assign string value for decimal value - c#

_item = new OutTYonetimOzet();
_item.Banka = Convert.ToDecimal(" ");
liste.Add(_item);
There is a list called liste. In List item Banka named element is decimal value. I want to show the empty string when I show it on the screen. But this code is getting an error that can not be cast. What is the problem.
Error message is:
Input string was not in a correct format.

There's no such thing as a "blank decimal". decimal cannot have a value that is "blank" - it always has a numeric value. Convert.ToDecimal(" ") is nonsensical - there is nothing it can return that makes sense.
You could try using a Nullable<decimal> (aka decimal?) perhaps; i.e.
public decimal? Banka {get;set;}
and
_item.Banka = null;

You can also use the decimal.TryParse instead of Convert. With this technique you can check if the string is valid.
_item = new OutTYonetimOzet();
decimal val = decimal.MinValue;
if (decimal.TryParse(" ", out val))
{
_item.Banka = val;
}
else
{
//your default goes here
_item.Banka = 0;
}
liste.Add(_item);
and as Mark suggested I would use Nullable<decimal> and use null as default value.

Related

Ignore dots in Convert.ToDecimal and return 0

I am using Convert.ToDecimal in linq, sometime amount value contains dot (.) as user want to write .50 or similar, as soon as they enter dot (using Numeric keypad from mobile), code is getting executed and throwing an exception.
I am getting string is not correct format exception for below code
var enteredAmountInTenders = TenderListCollection.Sum(x => Convert.ToDecimal(string.IsNullOrEmpty(x.Amount) ? "0" : x.Amount));
How can I ignore dot for above code and just get 0?
I would use decimal.TryParse instead of Convert.ToDecimal to cast the value.
var enteredAmountInTenders = TenderListCollection
.Sum(x => !decimal.TryParse(x.Amount,out var result) ? 0 : result);
you could check this before your set your property for the object in your TenderListCollection.
private string _amount = "0";
public string Amount
{
get
{
return _amount;
}
set
{
if(!string.IsNullOrEmpty(value))
{
if(value != ".")
{
_amount = value;
}
}
}
}
In general i dont like storing amounts as string, so i also would suggest to rename the Amount to GivenAmount and have an Amount Property which is a decimal, this way our code is clean and you dont need to parse in a Lambda expression.

Code not converting text

I have a textbox that allows users to input a decimal values that then gets stored in the a table in the database, this piece of code works in the development environment. I have now published the my project to the server and now is not longer taking the values with the decimal places.
decimal ReceiptAmount;
decimal AmountDue;
decimal Change;
if (!string.IsNullOrEmpty(((TextBox)dl_Item.FindControl("tb_ReceiptAmount")).Text))
{
if (((TextBox)dl_Item.FindControl("tb_ReceiptAmount")).Text.Contains(".") == true)
{
ReceiptAmount = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_ReceiptAmount")).Text.Replace(".", ","));
}
else
{
ReceiptAmount = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_ReceiptAmount")).Text);
}
}
else
{
ReceiptAmount = 0;
}
if (!string.IsNullOrEmpty(((TextBox)dl_Item.FindControl("tb_AmountDue")).Text))
{
if (((TextBox)dl_Item.FindControl("tb_AmountDue")).Text.Contains(".") == true)
{
AmountDue = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_AmountDue")).Text.Replace(".", ","));
}
else
{
AmountDue = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_AmountDue")).Text);
}
}
else
{
AmountDue = 0;
}
if (!string.IsNullOrEmpty(((TextBox)dl_Item.FindControl("tb_Change")).Text))
{
if (((TextBox)dl_Item.FindControl("tb_Change")).Text.Contains(".") == true)
{
Change = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_Change")).Text.Replace(".", ","));
}
else
{
Change = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_Change")).Text);
}
}
else
{
Change = 0;
}
I am not to sure what seems to be the problem with this piece of code. The Textbox are found in a datalist that I loop through to get all of the values.
The Convert.ToDecimal overload that takes a string as input will parse the string using the CultureInfo.CurrentCulture. Probably your server has different regional settings. Depending on regional settings, a comma or point may be either interpreted as a thousand separator (and thus ignored) or as the decimal separator.
Instead, you should use Decimal.Parse directly, providing either a specific culture or the invariant culture, depending on your use case.
Ideally, you'd set the culture of the user somewhere. To achieve this there are multiple approaches, e.g. for ASP.Net Web forms: https://msdn.microsoft.com/en-us/library/bz9tc508.aspx
If you parse the string using the correct culture, you can get rid of the string manipulation for replacing . with ,.
First of all, lines like
if (!string.IsNullOrEmpty(((TextBox)dl_Item.FindControl("tb_ReceiptAmount")).Text))
look very ugly; let's extract a method (copy/paste is very, very bad practice):
private String FindDLText(String controlName) {
var box = dl_Item.FindControl(controlName) as TextBox;
return box == null ? null : box.Text;
}
Then you don't need checking Text.Contains(".") == true, just Replace if you really need it:
private Decimal FindDLValue(String controlName) {
String text = FindDLText(controlName);
if (String.IsNullOrEmpty(text))
return 0.0M;
//TODO: check if you really need this
//text = text.Replace(".", ",");
// you have to specify Culture either InvariantCulture or some predefined one;
// say, new CultureInfo("ru-RU") // <- use Russian Culture to parse this
return Decimal.Parse(text, CultureInfo.InvariantCulture);
}
Finally, you can get
decimal ReceiptAmount = FindDLValue("tb_ReceiptAmount");
decimal AmountDue = FindDLValue("tb_AmountDue");
decimal Change = FindDLValue("tb_Change");
feel the difference: three evident lines and two simple methods.

For string I can use ToString. What to use for decimal? [duplicate]

This question already has answers here:
Convert string to decimal, keeping fractions
(12 answers)
Closed 8 years ago.
String ItemName=txtItemName.Text.ToString();
String ItemSpecification=txtItemSpecification.Text.ToString ();
String Category=cmbCategory.SelectedIndex .ToString();
String UnitOfMeasurement=cmbUnitOfMeasurement .SelectedIndex .ToString ();
Decimal Reorderlevel = txtReorderLevel.Text.();
Decimal LifeOfSpan=0;
String NeedApproval=rblNeedApprovalOrNotdx.SelectedItem.Value.ToString();
String Description=MemoDescription.Text.ToString ();
For string I can get a value using ToString. How can I get it for decimal?
Use Convert.ToDecimal() method to convert string to decimal.
The below code prints the value as 1200.00.
var convertDecimal = Convert.ToDecimal("1200.00");
Just in case it's cultural issues, try this version which shouldn't depend on your locale at all:
decimal d = decimal.Parse("1200.00", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));
I have always preferred using the Double.TryParse methods because it is going to spit back success or failure to convert without having to worry about exceptions.
string value;
double number;
value = Double.MinValue.ToString();
if (Double.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("{0} is outside the range of a Double.",
value);
Use Decimal.TryParse(), like this:
decimal Reorderlevel;
if (Decimal.TryParse(UnitOfMeasurement, out Reorderlevel))
{
// Conversion from string to decimal succeeded
}
else
{
// Conversion failed
}
Note: TryParse() does not thrown an exception if the attempted cast from string to decimal fails, but rather returns false when it fails and true when it succeeds.
UPDATE:
If you prefer to use a nullable decimal, then do this:
decimal tempValue;
decimal? Reorderlevel = Decimal.TryParse(UnitOfMeasurement, out tmpvalue) ?
tmpvalue : (decimal?)null;
Then you can check if Reorderlevel has a value before using it, like this:
if(Reorderlevel.HasValue)
{
// Do something with reorder level value here
}
Use Convert.ToDecimal() or Decimal.TryParse()
You can use the method Convert.ToDecimal() from the System namespace.

C# How to assign a string to a double

I need help figuring out how to assign a string to a double.
double value = "myString";
I have double value = double.Parse("myString"); but this throws a FormatException.
I have trying to concatenate like this:
string stringValue += doubleValue.toString() + intValue.ToString;
return stringValue;
I have double value = double.Parse("myString"); but this throws a string.Format error.
Yes, that's the behaviour you want in this case. "myString" doesn't have a numerical value, so the correct numerical value to give it, is to throw a formatting error.
double.Parse("1.2") would work or not depending on whether the culture in use was one where 1.2 was represented as "1.2" or as "1,2". double.Parse("1.2", CultureInfo.InvariantCulture) will always return 1.2, because it's specific about which culture to use.
double.TryParse is useful where it's likely for someone to pass an inappropriate string (like "myString") because it returns a boolean representing success or failure, rather than throwing an exception.
You can use TryParse
string x = "1234";
double y;
if(double.TryParse(x, out y))
{
Console.WriteLine("success y = " + y.ToString());
}
else
{
Console.WriteLine(x + " could not be converted to a double");
}
Parse it, assuming myString is a valid double string representation (eg "3.49", "1394.293", "-1.30E3")
double value = double.Parse(myString)
Most (All?) of the normal numerical types have parse methods. Use TryParse if you're unsure if it's valid (Trying to parse "abc" as a number will throw an exception)
#L.B For custom parsing you can define a NumberFormatInfo like this:
var a = new System.Globalization.NumberFormatInfo()
a.NumberDecimalSeparator = ",";
a.NumberGroupSeparator = ".";
double d = Double.Parse("1.000.000,5", a);
You cannot assign a string to a double. It's impossible. A double is a numerical type. A string is not.
If you parse a string that is a double it is possible.
var doubleThing = Double.Parse("9.99");
double.Parse(string);
Can and will through an exception if the format is incorrect. What are you trying to parse?
double.TryParse("1.05", out value);
Will return true or false if the parse succeeds or fails.

how to do this conversion?

string mvi = Moneys.GetValue(8) as string;
if (mvi == null)
// I am getting exception Here if its null?
money.Currency= Convert.ToDecimal("");
else
// Currency is Decimal
money.Currency= Convert.ToDecimal(mvi);
// I am getting exception Here if its null?
money.Currency= Convert.ToDecimal("");
Can anybody tell me how to do this?
Empty string is not convertible to decimal. You could perform a check like this
if (string.IsNullOrEmpty(mvi))
{
money.Currency = 0M;
}
else
{
decimal temp = 0M;
if (decimal.TryParse(mvi, out temp))
{
money.Currency = temp;
}
else
{
// you have an invalid input, handle
}
}
Here's my version of Anthony Pegram's answer:
string mvi = Moneys.GetValue(8) as string;
money.Currency = 0M;
if (!String.IsNullOrEmpty(mvi))
if (!Decimal.TryParse(mvi, out money.Currency))
throw new FormatException("mvi");
On the whole, it looks quite a bit like the one Alex made, only it treats empty as zero and shows more error-handling.
You can use TryParse instead of Convert.ToDecimal():
decimal theValue;
string mvi = Moneys.GetValue(8) as string;
Decimal.TryParse( mvi, out theValue );
alternatively, you can use the null coallescing operator to handle nulls preemtively:
var theValue = Convert.ToDecimal( mvi ?? "0" );
In both cases, however, you have to decide what to do if the value coming in is not a valid decimal.
http://msdn.microsoft.com/en-us/library/hf9z3s65.aspx
I think you want Convert.ToDecimal("0.0"); otherwise you get a EDIT: ArgumentNullException

Categories