Problems saving a Decimal using the Entity Framework

0

When I enter a quantity of a product, which is of the Decimal type, I use a TextBox:

decimal STOCK;
if(!decimal.TryParse(txtStock.Text, out STOCK))
{
    MessageBox.Show("Debe ingresar un valor correcto para el stock", "Advertencia");
    return;
}

I save the variable in producto.stock = STOCK , also valid from the TextBox event that a number with a comma is entered.

 private void txtStock_KeyPress(object sender, KeyPressEventArgs e)
{
    //if (e.KeyChar == 8)
    //{
    //    e.Handled = false;
    //    return;
    //}


    //bool IsDec = false;
    //int nroDec = 0;

    //for (int i = 0; i < txtStock.Text.Length; i++)
    //{
    //    if (txtStock.Text[i] == ',')
    //        IsDec = true;

    //    if (IsDec && nroDec++ >= 2)
    //    {
    //        e.Handled = true;
    //        return;
    //    }


    //}

    //if (e.KeyChar >= 48 && e.KeyChar <= 57)
    //    e.Handled = false;
    //else if (e.KeyChar == 44)
    //    e.Handled = (IsDec) ? true : false;
    //else
    //    e.Handled = true;
}

My problem is when I enter for example 0,5 saves it as 1 or if income 0,3 saves it as 0 .

    
asked by Patricio Rey Baccaro 23.01.2018 в 00:55
source

1 answer

0

Based on the comments, the problem you have is due to the definition of your table in your database.

For example, when you define the column STOCK as DECIMAL(18,0) rounding will be done at the time of insertion.

CREATE TABLE TABLA(
    STOCK DECIMAL(18,0)
)
INSERT INTO TABLA VALUES (15.5), (1), (0.5);
SELECT * FROM TABLA

You'll get:

+-------+
| STOCK |
+-------+
|    16 |
|     1 |
|     1 |
+-------+

To solve your problem, you have to modify your column and define the decimal digits. For example, STOCK DECIMAL(18, 4) . Where, the number of decimals will be 4 and the whole part of 14 digits.

If you want to modify through a query, you should do:

ALTER TABLE TABLA ALTER COLUMN STOCK DECIMAL(18, 4);

Reference:

answered by 23.01.2018 / 03:07
source