C#检查小数有超过3位小数? [英] C# Check if a decimal has more than 3 decimal places?
问题描述
我有我不能改变的情况:一个数据库表(表一)接受6位小数,而在不同的表(表二)相关的列只有3位小数。
I have a situation that I cannot change: one database table (table A) accepts 6 decimal places, while a related column in a different table (table B) only has 3 decimal places.
我需要从A复制到B,但如果有超过3位小数额外的数据将会丢失。我不能改变表的定义,但我可以添加一个解决方法。所以我试图找出如何检查小数有超过3位小数或不?
I need to copy from A to B, but if A has more than 3 decimal places the extra data will be lost. I cant change the table definition but I can add a workaround. So I'm trying to find out how to check if a decimal has more than 3 decimal places or not?
例如
Table A
Id, Qty, Unit(=6dp)
1, 1, 0.00025
2, 4000, 0.00025
Table B
Id, TotalQty(=3dp)
我希望能够找出是否数量*从表A股有超过3位小数(第1行会失败,排2将通过):
I want to be able to find out if Qty * Unit from Table A has more than 3 decimals (row 1 would fail, row 2 would pass):
if (CountDecimalPlaces(tableA.Qty * tableA.Unit) > 3)
{
return false;
}
tableB.TotalQty = tableA.Qty * tableA.Unit;
我将如何贯彻落实 CountDecimalPlaces(十进制值){}
函数
推荐答案
这适用于3位小数,它可以适用于一个通用的解决方案:
This works for 3 decimal places, and it can be adapted for a generic solution:
static bool LessThan3DecimalPlaces(decimal dec)
{
decimal value = dec * 1000;
return value == Math.Floor(value);
}
static void Test()
{
Console.WriteLine(LessThan3DecimalPlaces(1m * 0.00025m));
Console.WriteLine(LessThan3DecimalPlaces(4000m * 0.00025m));
}
对于一个真正的通用的解决方案,你需要解构十进制在其零部件的价值 - 看看 Decimal.GetBits 了解详情。
更新:这是一个简单的实现,它适用于它的整数部分小于long.MaxValue所有小数一个通用的解决方案(你需要像一个大整数为真实地通用的功能)。
Update: this is a simple implementation of a generic solution which works for all decimals whose integer part is less than long.MaxValue (you'd need something like a "big integer" for a trully generic function).
static decimal CountDecimalPlaces(decimal dec)
{
int[] bits = Decimal.GetBits(dec);
int exponent = bits[3] >> 16;
int result = exponent;
long lowDecimal = bits[0] | (bits[1] >> 8);
while ((lowDecimal % 10) == 0)
{
result--;
lowDecimal /= 10;
}
return result;
}
static void Foo()
{
Console.WriteLine(CountDecimalPlaces(1.6m));
Console.WriteLine(CountDecimalPlaces(1.600m));
Console.WriteLine(CountDecimalPlaces(decimal.MaxValue));
Console.WriteLine(CountDecimalPlaces(1m * 0.00025m));
Console.WriteLine(CountDecimalPlaces(4000m * 0.00025m));
}
这篇关于C#检查小数有超过3位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!