C# passing decimal value to SQL Server - c#

I'm working SQL Server database. Table column decimal(13,2) I send value from c# decimal type parameter.My problem's when send value 400.00 from c# but value saved 40000.00.Can you help me please?
decimal amount = Convert.ToDecimal(txttutar.Text,CultureInfo.InvariantCulture)
SqlCmd.Parameters.Add("#AMOUNT", SqlDbType.Decimal).Value = amount;

The symptoms you describe are a clear sign that your input doesn't match the InvariantCulture settings.
If your culture uses, as separator for decimal values, a comma or something else but a point, then converting a text using InvariantCulture could produce a wrong value.
For example, in my culture (it-IT) converting 400,00 (a correct decimal in it-IT) with InvariantCulture results in the mentioned value of 40000.
Use CultureInfo.CurrentCulture instead
decimal amount = Convert.ToDecimal(txttutar.Text,CultureInfo.CurrentCulture)
Said that, do not use Convert.ToDecimal to convert user input.
If the user types something that is not a valid decimal number (leaves the input blank or types a string like "ABC") the Convert.ToDecimal will throw an exception.
Instead use decimal.TryParse and check the output
decimal amount;
if(!decimal.TryParse(txttutar.Text, NumberStyles.None, CultureInfo.CurrentCulture, out amount))
// Message for your user -- Invalid number --
else
// go on with the database code....

This should help.
decimal amount = Convert.ToDecimal(txttutar.Text,CultureInfo.InvariantCulture)
SqlParameter amtParam = new SqlParameter("#AMOUNT", SqlDbType.Decimal);
amtParam.Precision = 13;
amtParam.Scale = 2;
amtParam.Value = amount;
SqlCmd.Parameters.Add(amtParam);

Related

How to compare currency or alphanumeric values in C#

The value that extracted from the application is in string format for ex. "$0.38". So, I segregated each character in the given string using IsDigit then appended them together using string builder. The digit can also be alphanumeric like "12,365.23 AS". Is there a way to recover only numeric part (along with the decimal) from the given string.
But Output I receive is "38" instead of "0.38". I also want to compare that the given string value lies between the upperLimit and lowerLimit provided.
Please let me know how to proceed with the same.
string Value = "$0.38";
int upperLimit = 2500;
int lowerLimit = 50000;
StringBuilder sb = new StringBuilder();
//sb.Append(someString);
foreach (char amin in Value)
{
if (System.Char.IsDigit(amin))
{
sb.Append(amin);
}
}
int compareVal = Convert.ToInt32(sb.ToString());
Console.WriteLine("value for comparision" + " " + compareVal);
The best way is using one of the overloads of decimal.Parse:
string Value = "$0.38";
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
decimal dd=decimal.Parse(Value, System.Globalization.NumberStyles.AllowCurrencySymbol|System.Globalization.NumberStyles.AllowDecimalPoint,culture);
Note the use of NumberStyles enum.That way you can control exaclty the parsing.
There are two reasons why you will get 38:
StringBuilder looks like "038", since "." is not a digit (just like "$").
Convert.ToInt32(...) returns an integer which doesn't allow decimal digits.
The better data type for currencies is decimal, a high precision floating point data type so to say.
Try
var amount = decimal.Parse(Value , NumberStyles.Currency)
var isInLimit = upperLimit <= amount && amount <= lowerLimit; // i guess you swapped upper and lower limit btw. ;)
instead.
Edit
In order to use the NumberStyles-Enumeration, you will have to use tha correct namespace in your file:
using System.Globalization;
You are omitting the decimal point and you are not using a decimal data type to hold the converted value. The real way to go is to convert the currency string to a decimal number:
CultureInfo usCulture = new CultureInfo("en-US)";
decimal amount = decimal.Parse(Value, NumberStyles.Currency, usCulture);
You can then perform a proper numeric comparison:
if (amount <= upperLimit && amount >= lowerLimit)
....
I first marked the question as a duplicate, but then changed my mind. I still think it is very much related to: Convert any currency string to double

How to convert string to decimal with 3 decimal places?

string num = 23.6;
I want to know how can I convert it into decimal with 3 decimal places
like
decimal nn = 23.600
Is there any method?
I try my best..
First of all your string num = 23.6; won't even compile. You need to use double quotes with your strings like string num = "23.6";
If you wanna get this as a decimal, you need to parse it first with a IFormatProvider that have . as a NumberDecimalSeparator like InvariantCulture(if your CurrentCulture uses . already, you don't have to pass second paramter);
decimal nn = decimal.Parse(num, CultureInfo.InvariantCulture);
Now we have a 23.6 as a decimal value. But as a value, 23.6, 23.60, 23.600 and 23.60000000000 are totally same, right? No matter which one you parse it to decimal, you will get the same value as a 23.6M in debugger. Looks like these are not true. See Jon Skeet comments on this answer and his "Keeping zeroes" section on Decimal floating point in .NET article.
Now what? Yes, we need to get it's textual representation as 23.600. Since we need only decimal separator in a textual representation, The "F" Format Specifier will fits out needs.
string str = nn.ToString("F3", CultureInfo.InvariantCulture); // 23.600
There are two different concepts here.
Value
View
you can have a value of 1 and view it like 1.0 or 1.0000 or +000001.00.
you have string 23.6. you can convert it to decimal using var d = decimal.Parse("23.6")
now you have a value equals to 23.6 you can view it like 23.600 by using d.ToString("F3")
you can read more about formatting decimal values
the thing that works for me in my case is num.ToString("#######.###")
A decimal is not a string, it does not display the trailing zeros. If you want a string that displays your 3 decimal places including trailing zeros, you can use string.Format:
decimal nn= 23.5;
var formattedNumber = string.Format("{0,000}", nn);

"Error converting" numeric input to correct TSQL type (possible Bug)

As of now I am encountering this kind of bug
Error converting data type float to decimal.
or
Error converting data type Numeric to decimal
This is my code
using (SqlConnection reportsConn = new SqlConnection(sqlConnWriter))
{
reportsConn.Open();
SqlCommand AddReconItem = new SqlCommand();
AddReconItem.Connection = reportsConn;
AddReconItem.CommandType = CommandType.StoredProcedure;
AddReconItem.CommandText = "Updater.usp_AddReconcileItems";
// AddReconItem.Parameters.Add("#varible",SqlDbType.Decimal
AddReconItem.Parameters.AddWithValue("#ITEMWEIGHT", Math.Round(Convert.ToDouble(WeightTextBox.Text+".00"), 2));
AddReconItem.Parameters.AddWithValue("#ITEMPRINCIPALAMT", Math.Round(Convert.ToDouble(PrincipalTexAmTextBox.Text + ".00"), 2));
AddReconItem.Parameters.AddWithValue("#FORLOANMONTH", Convert.ToDateTime(YearDropDownList.SelectedValue + "/" + MonthDropDownList.SelectedValue));
AddReconItem.Parameters.AddWithValue("#STORAGEGROUPID", StorageNameDropDownList.SelectedValue);
AddReconItem.Parameters.AddWithValue("#BRANCHCODE",BranchCodeTextBox.Text);
AddReconItem.Parameters.AddWithValue("RECONID", ReconTypeDropDownList.SelectedValue);
AddReconItem.Parameters.AddWithValue("#PAWNTIX",PwnTicketTextBox.Text);
AddReconItem.Parameters.AddWithValue("#CREATEDBY", Session["UserID"].ToString());
AddReconItem.ExecuteNonQuery();
}
When I input, 123 for principalamt and itemweight it accepts the answer and treats it as a decimal, but when I input 1234 for itemweight and still 123 for Principalamt it shows that error, if I remove the conversion and change it to Convert.ToDecimal it shows Error converting data type Numeric to decimal if I use it as text it shows Error converting data type varchar to decimal
Is this a bug or something? I can't seem to find a way I tried many options but none of them have been working
My database columns are below:
I really hope you can help me understand this phenomenon
EDIT
This is the first time I saw a program accepting 123 as a valid input while 1234 is not, my database Decimal (38,6) is very large enough to accommodate this input that's why I'm looking for the answer or known bugs that can solve this problem, thank you.
I'd suggest using Decimal.TryParse instead of Convert for your principalamt value and then maybe debugging and inspecting how the value gets converted to a valid Decimal for your Money column. For example something like;
bool valid;
var dbl = Convert.ToDouble("1234.00");
valid = Double.TryParse("1234.00", out dbl);
var dcml = Convert.ToDecimal("1234.00");
valid = Decimal.TryParse("1234.00", out dcml);
I'm not sure if you should be using Double as a data type when trying to store the resultant value in a Decimal field. Double represents floating type numbers and I think you should be using the Decimal data type for your Money column as mentioned in this answer.
For ItemWeight, with a data type of decimal(38,6), you'll end up with 6 decimal places regardless of your rounding I think. Try the following in SQL Server and make sure the parameter type for #ITEMPRINCIPALAMT is DECIMAL as well (similar to my example below).
DECLARE #Var decimal(38,6) = 1234.00
DECLARE #Tbl AS TABLE
(
Test decimal(38,6)
)
INSERT INTO #Tbl (Test) Values (#Var)
SELECT * FROM #Tbl

Changing the number of integers on a output value after the decimal point

So I'm learning and practicing WP7 application development.
I'm working with integers (currency), and it seems to always display four integers after the decimal place. I'm trying to cut it down to just either ONE or TWO decimal places.
I've been trying to use the "my variable.ToString("C2")" (C for Currency, 2 for number of ints after the decimal)
I'm probably missing something obvious, but please help
decimal number = new decimal(1000.12345678);
string text = number.ToString("#.##");
Output:
1000,12
An other way:
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencyDecimalDigits = 2;
decimal val = new decimal(1000.12345678);
string text = val.ToString("c", nfi);
When formatting a currency, NumberFormatInfo allows specifying following properties as well:
CurrencyDecimalDigits
CurrencyDecimalSeparator
CurrencyGroupSeparator
CurrencyGroupSizes
CurrencyNegativePattern
CurrencyPositivePattern
CurrencySymbol
See Custom Numeric Format Strings on MSDN for more examples
The "C" format string defines the currency specifier as described on MSDN. This will include the currency symbol for the current culture, or for a specific culture if supplied, e.g.
double amount = 1234.5678;
string formatted = amount.ToString("C", CultureInfo.CreateSpecificCulture("en-US"));
// This gives $1234.56
In your case, it seems that you have a limited set of currency symbols that you support, so I would suggest using the fixed point format specifier "F" instead. By default this will give you 2 decimal points, but you can specify a number to vary this, e.g.
double amount = 1234.5678;
string formatted = amount.ToString("F");
// This gives 1234.56
formatted = amount.ToString("F3");
// This gives 1234.567
Using the fixed point specifier will give you control over the number of decimal points and enable you to concatenate the currency symbol.
The only thing I would add to "sll" answer is to pay attention on Culture (they often forget to mantion this), like this (example)
string text = val.ToString("#.##", CultureInfo.InvariantCulture);
double total = 526.4134
string moneyValue = total.ToString("c");
This will display it in this format: $#.##

Convert string to decimal with format

I need convert a String to a decimal in C#, but this string have different formats.
For example:
"50085"
"500,85"
"500.85"
This should be convert for 500,85 in decimal. Is there is a simplified form to do this convertion using format?
Some cultures use a comma to indicate the floating point. You can test this with the following code on an aspx page:
var x = decimal.Parse("500,85");
Response.Write(x + (decimal)0.15);
This gives the answer 501 when the thread culture has been set to a culture that uses the comma as floating point. You can force this like so:
var x = decimal.Parse("500,85", new NumberFormatInfo() { NumberDecimalSeparator = "," });
While decimal.Parse() is the method you are looking for, you will have to provide a bit more information to it. It will not automatically pick between the 3 formats you give, you will have to tell it which format you are expecting (in the form of an IFormatProvider). Note that even with an IFormatProvider, I don't think "50085" will be properly pulled in.
The only consistent thing I see is that it appears from your examples that you always expect two decimal places of precision. If that is the case, you could strip out all periods and commas and then divide by 100.
Maybe something like:
public decimal? CustomParse(string incomingValue)
{
decimal val;
if (!decimal.TryParse(incomingValue.Replace(",", "").Replace(".", ""), NumberStyles.Number, CultureInfo.InvariantCulture, out val))
return null;
return val / 100;
}
This will work, depending on your culture settings:
string s = "500.85";
decimal d = decimal.Parse(s);
If your culture does not by default allow , instead of . as a decimal point, you will probably need to:
s = s.Replace(',','.');
But will need to check for multiple .'s... this seems to boil down to more of an issue of input sanitization. If you are able to validate and sanitize the input to all conform to a set of rules, the conversion to decimal will be a lot easier.
Try this code below:
string numValue = "500,85";
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("fr-FR");
decimal decValue;
bool decValid = decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat, out decValue);
if (decValid)
{
lblDecNum.Text = Convert.ToString(decValue, culInfo.NumberFormat);
}
Since I am giving a value of 500,85 I will assume that the culture is French and hence the decimal separator is ",". Then decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat,out decValue);
will return the value as 500.85 in decValue. Similarly if the user is English US then change the culInfo constructor.
There are numerous ways:
System.Convert.ToDecimal("232.23")
Double.Parse("232.23")
double test;
Double.TryParse("232.23", out test)
Make sure you try and catch...
This is a new feature called Digit Grouping Symbol.
Steps:
Open Region and Language in control panel
Click on Additional setting
On Numbers tab
Set Digit Grouping Symbol as custom setting.
Change comma; replace with (any character as A to Z or {/,}).
Digit Grouping Symbol=e;
Example:
string checkFormate = "123e123";
decimal outPut = 0.0M;
decimal.TryParse(checkFormate, out outPut);
Ans: outPut=123123;
Try This
public decimal AutoParse(string value)
{
if (Convert.ToDecimal("3.3") == ((decimal)3.3))
{
return Convert.ToDecimal(value.Replace(",", "."));
}
else
{
return Convert.ToDecimal(value.Replace(".", ","));
}
}

Categories

Resources