0

I need to store a value taken from a form into a column which is a decimal(4,0).

First (in the controller) I take the value from the form and I convert it from string to decimal and multiply it for 100 so I'm able to keep the values I need

//"12.34" --> (12.34)*100 --> 1234
item.DECIMAL_VALUE = decimal.Parse(view.decimal_value) * 100;

I checked in debug mode: the value into item.DECIMAL_VALUE is effectively a decimal and its value is 1234 (as expected).

Going on with the code I come to the point where I need to save the value into the database

_context.TABLE.Add(item);
return _context.SaveChanges();

And that's the problem. I get a DbUpdateException because it tries to save 1234,00 (which doesn't correspond to the decimal(4,0)) instead of 1234

Any ideas on why it's doing it and how to solve?

perlice
  • 87
  • 6

1 Answers1

0

If you want to stick to decimal(4,0) which is practically an integer you should also change the type of the variable DECIMAL_VALUE to a true integer in the item class.

After that, just to avoid potential retyping problems, you should also use explicit retyping when assigning the value...

item.DECIMAL_VALUE = (int)(decimal.Parse(view.decimal_value) * 100);
Petrroll
  • 741
  • 7
  • 29
  • Changing the type of `DECIMAL_VALUE` just got me more errors so I tried to keep it as it is and set its value as you suggested with `item.DECIMAL_VALUE = (int)(decimal.Parse(view.decimal_value) * 100);` and now it works! Thank you :) The only thing I can't understand is why was it adding the two zeroes? I have other decimal like that and I never got this problem – perlice Aug 07 '14 at 07:13
  • I don't know how it works but one might guess that it calls .ToString() function on the variable which (in case of decimal type) results in formatting with two decimal numbers. The reason why you had to use the (int) is quite simple, btw. While c# has some sort of implicit retyping it works only in cases where no data can be lost (e.g. int to decimal). In this case, however, data can be lost (decimal info) so you have to specify that you really want to do it (assign decimal value into an int). – Petrroll Aug 07 '14 at 12:48