获取小数点前的位数 [英] Get number of digits before decimal point
问题描述
我有一个 decimal
类型的变量,我想检查其中的小数点前的位数。
我应该怎么办?例如, 467.45
应该返回 3
。
I have a variable of decimal
type and I want to check the number of digits before decimal point in it.
What should I do? For example, 467.45
should return 3
.
推荐答案
不转换为 string
的解决方案(对于外来文化可能是危险的):
Solution without converting to string
(which can be dangerous in case of exotic cultures):
static int GetNumberOfDigits(decimal d)
{
decimal abs = Math.Abs(d);
return abs < 1 ? 0 : (int)(Math.Log10(decimal.ToDouble(abs)) + 1);
}
注意,该解决方案对所有十进制值均有效
更新
实际上,此解决方案不适用于某些大型应用值,例如: 999999999999998
, 999999999999999
, 9999999999999939
。 ..
In fact this solution does not work with some big values, for example: 999999999999998
, 999999999999999
, 9999999999999939
...
显然,具有 double
的数学运算不足以完成此任务。
Obviously, the mathematical operations with double
are not accurate enough for this task.
在搜索错误值时,我倾向于使用本主题中提出的基于 string
的替代方案。对我而言,这就是它们更可靠,更易于使用的证据(但请注意文化)。不过,基于循环的解决方案可以更快。
While searching wrong values I tend to use string
-based alternatives proposed in this topic. As for me, that is the evidence that they are more reliable and easy-to-use (but be aware of cultures). Loop-based solutions can be faster though.
感谢评论员,让我感到羞耻,对您有帮助。
Thanks to commentators, shame on me, lesson to you.
这篇关于获取小数点前的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!