I wrote up a quick c# extension method, but wasn't sure if there was a cleaner way to accomplish what I want to do. It does work, but feels slightly hacky using the string repeater, and inserting a decimal.
Goal is that at the application level, we can clean / fix any data problems before sending off to the database to prevent overflows.
Note: PCL Library, cant reference outside DLL's in this case.
public static bool TsqlDecimalBoundariesCheck(this decimal valueToCheck, int precision, int scale)
{
if(scale > precision) throw new ArgumentException($"BOUNDARY CHECK: Scale [{scale}] must not be higher than Percision [{precision}]");
// create X precision values of the value 9
var precisionValue = new string('9', precision);
// Insert the decimal place x positions from the right
if (scale > 0)
{
precisionValue = precisionValue.Insert((precision - scale), ".");
}
// Get the upper and lower values
var upperBoundry = decimal.Parse(precisionValue);
var lowerBoundry = upperBoundry * -1;
return (valueToCheck <= upperBoundry) && (valueToCheck >= lowerBoundry);
}
And some quick unit tests to accompany it:
[TestMethod]
public void TestBoundryConstraints()
{
var precision = 4;
var scale = 1;
var testValue = 1000m;
var result = testValue.TsqlDecimalBoundariesCheck(precision , scale);
Assert.IsFalse(result, $"Value {testValue} is expected to be outside Decimal({precision }, {scale})");
testValue = -1000m;
result = testValue.TsqlDecimalBoundariesCheck(precision , scale);
Assert.IsFalse(result, $"Value {testValue} is expected to be outside Decimal({precision }, {scale})");
testValue = 100m;
result = testValue.TsqlDecimalBoundariesCheck(precision , scale);
Assert.IsTrue(result, $"Value {testValue} is expected to be within Decimal({precision }, {scale})");
testValue = 999.9m;
result = testValue.TsqlDecimalBoundariesCheck(precision , scale);
Assert.IsTrue(result, $"Value {testValue} is expected to be within Decimal({precision }, {scale})");
testValue = -999.9m;
result = testValue.TsqlDecimalBoundariesCheck(precision , scale);
Assert.IsTrue(result, $"Value {testValue} is expected to be within Decimal({precision }, {scale})");
}