简体   繁体   English

在 C# 中验证十进制以在 SQL Server 中存储

[英]Validating decimal in C# for storage in SQL Server

I have a decimal database column decimal (26,6) .我有一个十进制数据库列decimal (26,6)

As far as I can gather this means a precision of 26 and a scale of 6.据我所知,这意味着精度为 26,比例为 6。

I think this means that the number can be a total of 26 digits in length and 6 of these digits can be after the decimal place.我认为这意味着该数字的总长度可以为 26 位,其中 6 位可以在小数位后。

In my WPF / C# frontend I need to validate an incoming decimal so that I can be sure that it can be stored in SQL Server without truncation etc.在我的 WPF/C# 前端,我需要验证传入的十进制数,以便我可以确保它可以存储在 SQL Server 中而不会被截断等。

So my question is there a way to check that decimal has a particular precision and scale.所以我的问题是有一种方法可以检查小数是否具有特定的精度和比例。

Also as an aside I have heard that SQL Server stores decimal in a completely different way to the CLR, is this true and if so is it something I need to worry about?另外顺便说一句,我听说 SQL Server 以与 CLR 完全不同的方式存储十进制,这是真的吗?如果是这样,我需要担心吗?

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.确定给定精度,十进制数的小数位数是否大于 26,6 的直接方法是检查其等效字符串的长度。

    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. C# 十进制数据类型的最大精度似乎是 29 位,而 SQL 十进制可以有 38 位。 So you may not be hitting the maximum value of SQL decimal from C#.所以你可能没有达到 C# 中 SQL 十进制的最大值。

If you already know destination scale and precision of decimal type at compile time, do simple comparison.如果您在编译时已经知道十进制类型的目标小数位数和精度,请进行简单比较。 For decimal(13,5):对于十进制(13,5):

public static bool IsValidDecimal13_5(decimal value)
{
    return -99999999.99999M <= value && value <= 99999999.99999M;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM