division making zeros after decimal point in c# - c#

I am doing below code in c#
obj.value = decimal_value / 100;
Where obj.value is a decimal variable in the model
decimal_value is a variable holding a decimal value
C# code
if (member["LOADINGS"] != "")
{
decimal loading_temp = Convert.ToDecimal(member["LOADINGS"]);
prem.loadings = loading_temp / 100m;
}
When debugged prem.loading gets correct value 0.0952 but when it get saved in sql server it shows 0.09000
loading variable in model
public decimal? loadings {get;set;}
eg: result
9.52/100 gives 0.0952 but when it stores in sql server in a column of datatype decimal(18,5) it gives the result 0.0900
Any idea for this ?
Edit
saving in database
premium prem = new premium();
if (member["LOADINGS"] != "")
{
decimal loading_temp = Convert.ToDecimal(member["LOADINGS"]);
prem.loadings = loading_temp / 100m;
}
db.premium.add(prem);
db.savechanges();

In SQL Server:
declare #v decimal(18,5)
select #v = 9.52/100
select #v
returns 0.09520

Related

Error while performing compute SUM() in a column

I've tried to compute a column in my datagrid, i will be showing these in my code as per below. I Keep getting these error.
I've go through these links
1. How To Convert The DataTable Column type?
2. Error while taking SUM() of column in datatable
3. Invalid usage of aggregate function Sum() and Type: String
//This is the column i add into my datagrid
MITTRA.Columns.Add("Min_Tol");
MITTRA.Columns.Add("Max_Tol");
MITTRA.Columns.Add("Min_Weight");
MITTRA.Columns.Add("Max_Weight");
// The following codes is working finely
// if you notice MTTRQT column, it's a data queried from database
for (int i = 0; i <= MITTRA.Rows.Count - 1; i++)
{
string item = MITTRA.Rows[i]["MTITNO"].ToString();
Tolerancechecking = database_select4.LoadUser_Tolerance(item);
MITTRA.Rows[i]["Min_Tol"] = Tolerancechecking.Rows[0]["Min_Tol"].ToString();
MITTRA.Rows[i]["Max_Tol"] = Tolerancechecking.Rows[0]["Max_Tol"].ToString();
MITTRA.Rows[i]["Min_Weight"] = Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) - ((Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) * Convert.ToDecimal(MITTRA.Rows[i]["Min_Tol"]) / 10));
MITTRA.Rows[i]["Max_Weight"] = Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) + ((Convert.ToDecimal(MITTRA.Rows[i]["MTTRQT"]) * Convert.ToDecimal(MITTRA.Rows[i]["Max_Tol"]) / 10));
dataGrid2.Columns.Clear();
dataGrid2.ItemsSource = null;
dataGrid2.ItemsSource = Tolerancechecking.DefaultView;
}
//Working Sum computation
Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(MTTRQT)", string.Empty));
MaxTol.Text = Sum.ToString(); /*** This is working as i got my value on the text box ****/
Errors when trying sum computation for different column
Initial try
1. Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(Min_Weight)", string.Empty));
Errors occurred
Invalid usage of aggregate function Sum() and Type: String.
Second Attempts
2. Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(Convert(Min_Weight,'System.Decimal'))", string.Empty));
3. Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(Convert(Min_Weight,'System.Decimal'))", ""));
Errors occurred
Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier.
How am i going to get the compute sum function to work?
Thank you #NoChance for the solutions. Hope this post can help others too.
/***** This is the part where i declare my datacolumn data type ****/
DataColumn Min_Weight = new DataColumn("Min_Weight");
Min_Weight.DataType = System.Type.GetType("System.Decimal");
MITTRA.Columns.Add(Min_Weight);
/**** This Works finally *****/
Decimal Sum = Convert.ToDecimal(MITTRA.Compute("SUM(Min_Weight)", string.Empty));
MaxTol.Text = Sum.ToString();

How to handle NULLIF and ISNULL of SQL statements in C# ASP.net?

I have some SQL statements (written by someone else) which I am trying to understand. In this SQL, it calculates 'Weight' as shown below.
ISNULL(NULLIF(CASE WHEN ISNULL(m.Override,0) = 1
THEN m.OverWeight
ELSE ISNULL(itemWeight.Weight,groupWeight.Weight) END,0),5) AS Weight
Now I have to use this logic in ASP.net. Since I am new to C#, ASP.net and SQL, I am struggling on it. I have done following so far.
//Calculate weight
bool override = DataConversion.GetBoolean(row["Override"]);
decimal overWeight = DataConversion.GetDecimal(row["OverWeight"]);
decimal itemWeight = DataConversion.GetDecimal(row["ItemWeight"]);
decimal groupWeight = DataConversion.GetDecimal(row["GroupWeight"]);
decimal weight= override? DataConversion.GetDecimal(row["OverWeight"]): 5;
var par = new par(
Id: DataConversion.GetInt(row["MaterialId"]),
weight: weight
);
The issue I am facing is:
how do I use ELSE ISNULL(itemWeight.Weight,groupWeight.Weight in my condition statement?
i.e.decimal weight= override?DataConversion.GetDecimal(row["OverWeight"]): 5;.
I found it easier to tackle with better formatting - makes it clear what goes where:
ISNULL(
NULLIF(
CASE
WHEN ISNULL(m.Override,0) = 1
THEN m.OverWeight
ELSE
ISNULL(itemWeight.Weight,groupWeight.Weight)
END,
0
),
5
) AS Weight
Now just using definitions of ISNULL and NULLIF I got this code:
decimal weight; // AS Weight
if (override != null && override == 1) // WHEN ISNULL(m.Override,0) = 1
{
weight = overWeight; // THEN m.OverWeight
}
else
{
if (itemWeight != null) // ELSE ISNULL(...)
weight = itemWeight; // itemWeight.Weight
else
weight = groupWeight; // groupWeight.Weight
}
if (weight == 0) // NULLIF(..., 0)
{
weight = 5; // ISNULL(..., 5)
}
You way need to test against actual DBNull though, depends on where your data comes from.

CRM Plugin not working C#

I am making a plugin that is supposed to take data from Quote Product entity.
By default, there is no discount in percent field, just discount amount. I added Discount% filed to the form (ad_discountpercent). Now I should calculate new price like this:
sum = (price - discount)*quantity*(100 - discount%)/100
I made a code for that. When i build this code there are no errors, but there are no changes in the CRM. I have also registered my plugin.
There are 3 fields manualdiscountamount , priceperunit , extendedamount that are Currency type fields. quantity is decimal and ad_discountpercent is integer. I have found a few methods for getting value from Currency, some are commented, some are not, because I don't know which one is proper.
One notice i checked fetch results, and they are as expected, so fetch is working fine. I compressed it in one line, because of the code length.
Here is the part of the code that should do the job. I have no information is there anything wrong with conversion, am I using proper way to set a new value?
I am new in this, so any comment would help me.
string fetch1 = #"<fetch count='50' ><entity name='quotedetail' ><attribute name='manualdiscountamount' /><attribute name='priceperunit' /><attribute name='ad_discountpercent' /><attribute name='quantity' /> <attribute name='extendedamount' /> <filter> <condition attribute='ad_discountpercent' operator='not-null'/> </filter > </ entity> </fetch>";
EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetch1));
foreach (var c in result.Entities)
{
// int discountPer = (int)c.Attributes["ad_discountpercent"];
int discountPer = c.GetAttributeValue<int>("ad_discountpercent");
Money m = (Money)c.Attributes["priceperunit"];
decimal price = m.Value;
// decimal price = c.GetAttributeValue<decimal>("priceperunit");
Money m1 = (Money)c.Attributes["manualdiscountamount"];
decimal discount = m1.Value;
// decimal discount = c.GetAttributeValue<decimal>("manualdiscountamount");
//decimal discountPer = Convert.ToDecimal( c.Attributes["ad_discountpercent"]);
decimal quantity = Convert.ToDecimal(c.Attributes["quantity"]);
//decimal quantity = c.GetAttributeValue<decimal>("quantity");
decimal sum = (price - discount) * quantity * (100 - discountPer) / 100;
Money summTotal = new Money();
summTotal.Value = sum;
entity["extendedamount"] = summTotal;
service.Update(entity);
ExtendedAmount is an auto-calculated field based on priceperunit and quantity. So any updates to this field will be ignored by CRM.
Instead update the priceperunit and quantity to get the desired extendedamount.
entity["priceperunit"] = new Money((price - discount) * quantity * (100 - discountPer) / 100);
entity["quantity"] = 1;
service.Update(entity);
Is it possible that your query isn't returning any data, therefore your loop is never dropped into and your update never executes?
As previously suggested, take a look at how to debug a plugin via the plugin profiler.
Or, if you don't want to do that. Throw an temporary exception in your code after you do the RetrieveMultiple and in the message, add in the result.Entities.Count value to confirm how many records you're getting back.

Change textbox text according to text in another textbox

I am doing a web form application. In this form, I have three textbox and one of them show the result of the nuktiplication of the other two textbox.Let say three textboxes are txtMulti1, txtMulti2 and txtMultiRst.
This is my code so far, but not working
public txtMultiRst_TextChange( obeject sender, EventArgs e) {
int result = int.Parse(txtMultRst.Text);
result = int.Parse(txtMulti1.Text) * int.Parse(txtMulti2.Text);
}
The way I was thinking is txtMuli1 * txtMulti2 and the answer should display in txtMulRst. Help will be great thanks
You should set txtMultRst.Text property.
int result = int.Parse(txtMulti1.Text) * int.Parse(txtMulti2.Text);
txtMultRst.Text = result.ToString();
In your case, you are creating new variable result and set value to it, not to the txtMultRst.Text, because int is a value type.
Also, I suggest to use TryParse instead of Parse, to handle situation when txtMulti1.Text is not parseble to int.
int value1 = 0;
int value2 = 0;
if (int.TryParse (txtMulti1.Text, out value1) && int.TryParse (txtMulti2.Text, out value2))
{
int result = value1 * value2;
txtMultRst.Text = result.ToString();
}
Given this is a user-input field I can't recommend Int32.TryParse strongly enough. Otherwise the first time they enter something that is not a number it will throw an exception.
Try something like this:
int n1, n2;
if(Int32.TryParse(txtMulti1.Text, out n1) && Int32.TryParse(txtMulti2.Text, out n2)
txtMultRst.Text = (n1*n2).ToString();
else
txtMultRst.Text = "Please enter valid numbers only";

Decimal Rounding in C#

I have code that is taking information from the database to insert into a list. One piece of data that I'm taking will be used for price. (I set its type to decimal in SQL Server), for example: " 1,80".
But when I select it, my decimal variable returns the value 2 !
I want to know if there are a simple way to make decimal not automatically round numbers.
This is the code:
public decimal preco { get; set; }
while (dr.Read())
{
clsCaProd oProd = new clsCaProd();
oProd.cod = dr.GetInt32(0);
oProd.preco = dr.GetDecimal(1); // Here returns "2" instead of "1,80"
oProd.info = dr.GetString(2);
oProd.categ = dr.GetString(3);
oProd.nome = dr.GetString(4);
lProd.Add(oProd);
}
If you declare a column as decimal, the default "scale" is zero. You need to specify the precision and scale.
Try this example:
declare #d1 decimal = 1.80
declare #d2 decimal(19,4) = 1.80
select #d1, #d2;
Results:
2 1.8000

Categories

Resources