LukaCindric
LukaCindric

Reputation: 3

How to save a decimal number from c# to sql

I'm having a problem when I try to save a decimal number from c# to sql database. First of all I have string that I convert to decimal and when I try to save that decimal to sql database something goes wrong. For example if I try to save 3.24, in database it shows as 324.00 this is the part of the code please help... I have already tried changig types from decimal to numeric and instead of convert.ToDecima decimal.Parse

        decimal cijena_uzine = Convert.ToDecimal(textBox1.Text, CultureInfo.InvariantCulture.NumberFormat);

        try
        {
            spremi_cijenu_obroka.Open();
            cmd = new SqlCommand("Update Vrsta_Obroka set cijena="+ cijena_uzine + " where Šifra_Obroka=1 ;", spremi_cijenu_obroka);

Upvotes: 0

Views: 3993

Answers (2)

LukaCindric
LukaCindric

Reputation: 3

I left the variable as a string and it somehow works...

string cijena_uzine = textBox1.Text;             
        try
        {
            spremi_cijenu_obroka.Open();
            cmd = new SqlCommand("Update Vrsta_Obroka set cijena=" +cijena_uzine + " where Šifra_Obroka=1 ;", spremi_cijenu_obroka);

Upvotes: 0

Szymon
Szymon

Reputation: 43023

I'm just guessing but you probably enter the number as 3,24 with comma as decimal separator (as most countries in Europe do).

This converts to 324 when you use CultureInfo.InvariantCulture.NumberFormat.

Change you code to below to use your culture:

decimal cijena_uzine = Convert.ToDecimal(textBox1.Text, System.Globalization.CultureInfo.CurrentCulture);

Upvotes: 1

Related Questions