Decimal Rounding Problem
I have a textbox which is restricted to decimal input but the sql table has restriction on the column that it is Decimal(18,2). So the error is people are able to enter more than 18 digits + as many as digits after decimal but if i still do a
Math.Round(decimal,intDigits);
then the digits before the decimal will exceed 18 and will shoot me an error. So the question is how to Round a decimal with t开发者_开发问答his restrictions.Decimal(18,2).
if you need to restrict number of digits before the decimal point the rounding can't help you here. i would validate text box input with regular expression to restrict number of digits before and after the decimal point.
For the SQL Decimal(p,q)
data type, p specifies the total precision (number of decimal digits), and q specifies the scale (number of digits to the right of the decimal point). In you case (decimal(18,2)
), you've got 18 decimal digits, the rightmost 2 of which are to the right of the decimal point.
What you need to to is put validation constraints on your text box. You can
use a regular expression to do the validation. The regular expression
^-?\d{1,16}(\.\d{1,2})?$
would do the trick. Omit the optional minus sign if you don't want them to be able to enter negative numbers.you could validate against a range: convert to
Decimal
, then check to see if it is within the valid range of values.
By rounding the decimal you can jump into the Decimal rounding problems. To avoid this you can try do to something like this.
int myDecimalInt = myDecimal * (10 * intDigits);
This will give you concrete Integer with all numbers after the point truncated with desired precision: intDigits
.
Or you can try to handle it on UI side: do not let a user to insert more digits then you can support.
精彩评论