简体   繁体   中英

Decimal.Parse Issue

I have a problem with decimal parse, I know this question been asked a loot, but none of the solution worked for me, and i've been stuck in here for two days now.

My problem is my CultureInfo is set to fr_Fr and when i put the code below an error shows caused with comma that separates decimal instead of period.

double entree = Convert.ToDouble(row["entree"]);
double sortie = Convert.ToDouble(row["sortie"]);
int id_mw = Convert.ToInt32(row["mouvment_w_id"]);

qte_Stock += entree - sortie;
decimal qte_s ;

MessageBox.Show("" + CultureInfo.CurrentCulture);
qte_s = Decimal.Parse(Convert.ToString(qte_Stock), NumberStyles.Number ^ NumberStyles.AllowThousands);

MessageBox.Show("" + qte_s);
qte.CommandText = "Update tcpos.dbo.Warehouse_mouvement set qte_stock= " + qte_s + " where mouvment_w_id = "+id_mw;
qte.ExecuteNonQuery();

What's the type of qte_Stock

...

it was a decimal

...

Then you have your answer since you want to make it a decimal.

Pass the decimal as Parameter to prevent sql-injection and this issue(decimal separator).

For example(assuming SQL-Server as rdbms):

using(var con = new SqlConnection(connectionString))
using(var cmd = new SqlCommand("Update tcpos.dbo.Warehouse_mouvement set qte_stock=@qte_stock where mouvment_w_id = @mouvment_w_id", con))
{
    cmd.Parameters.AddWithValue("@qte_stock", qte_stock);
    cmd.Parameters.AddWithValue("@mouvment_w_id", id_mw);
    con.Open();
    cmd.ExecuteNonQuery();
}
qte_s = qte_Stock.ToString ("#.#", System.Globalization.CultureInfo.InvariantCulture);

This will solve, if your problem is because in your culture (like mine), the comma seaparates decimals, and not thousands.

Also, use parameterized SQL, like Damien_The_Unbeliever and Jonh Skeet said.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM