小数值应为 0.0x 时却为零
如果之前讨论过这个问题,我很抱歉,我很难找到这个问题。
我正在计算折旧率。我们计算的一部分是 1/寿命(以月为单位)。我的表将此数据存储在十进制
字段中。我尝试了 test = 1 /estimatedLife;
但 test
的计算结果(定义为 decimal
)为 0
。预计寿命为36个月。所以 1/36 应等于 0.02777778。
对我做错了什么有什么想法吗?
顺便说一句,我将 test
更改为 double 并得到了相同的结果。
If this was previously talked about, I'm sorry, I had a hard time searching on this.
I am calculating a depreciation rate. One portion of our calculation is 1/life in months. My table stores this data in a decimal
field. I tried test = 1 / estimatedLife;
but the result of the calculation of test
(which is defined as a decimal
) is 0.
Say the estimated life is 36 months. So 1/36 should equal 0.02777778.
Any thoughts of what I am doing wrong?
BTW, I changed the test
to a double and had the same result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
另一个内置替代方案是 Decimal.Divide:
还有更多要写的,但我想说得相当明确。
Another built-in alternative is Decimal.Divide:
More to write, but pretty explicit I'd say.
尝试:
try:
您的代码将两个整数相除,然后将结果(也是一个整数)分配给一个
decimal
变量。您需要通过将至少一个操作数设为
十进制
来切换到十进制
除法,如下所示:1.0M /estimatedLife
。Your code divides two integers, then assigns the result (which is also an integer) to a
decimal
variable.You need to switch to
decimal
division by making at least one of the operands adecimal
, like this:1.0M / estimatedLife
.estimatedLife 是一个 int,不是吗?试试这个:
或者使用 SwDevMan81 的建议:
问题是整数除法会丢弃小数点后的所有内容。其中一个参数必须是小数才能得到您想要的结果。
他在评论中发布的文档链接说:
因此 1.0M 表示“值为 1.0 的十进制类型的文字”
estimatedLife is an int, isn't it. Try this:
or use SwDevMan81's suggestion:
The issue is that integer division throws away everything after the decimal point. One of the arguments has to be a decimal for you to get the result you want.
The documentation link that he posted in a comment says:
so 1.0M means "a literal of type decimal with the value 1.0"
只是补充一下,如果您需要特定的精度(我注意到您的输出设置为小数点后 8 位),您可以使用
just to add, if you require a specific precision (I noticed your output was set to 8 decimal places) you can use