Validating decimal in C# for storage in SQL Server

ⅰ亾dé卋堺 提交于 2019-12-04 17:07:23

straight forward way to determine if a given precision,scale of decimal number is greater than 26,6 would be to check the length of its string equivalent.

    public static bool WillItTruncate(double dNumber, int precision, int scale) {
        string[] dString = dNumber.ToString("#.#", CultureInfo.InvariantCulture).Split('.');
        return (dString[0].Length > (precision - scale) || dString.Length>1?dString[1].Length > scale:true);
    }

The maximum precision for C# decimal datatype seems to be 29 digits whereas SQL decimal can have 38 digits. So you may not be hitting the maximum value of SQL decimal from C#.

If you already know destination scale and precision of decimal type at compile time, do simple comparison. For decimal(13,5):

public static bool IsValidDecimal13_5(decimal value)
{
    return -99999999.99999M <= value && value <= 99999999.99999M;
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!