问题描述
如何检查数字是否可以被特定数字整除或两个数字都不都是小数.小数点后两位数字的值.我曾经尝试过(((dn / size) % 1) == 0)
,但在某些情况下不能提供适当的输出.我该如何解决.在这里我放一些示例值,例如double dn = 369.35,369.55.370.55
和大小可能是0.05,0.10,0.5
等...
How can i check number is divisible by particular number or not both numbers are decimal. with decimal point value of two digits.i had tried with below(((dn / size) % 1) == 0)
but in some cases it not provide proper out put.how can i resolve it. here i put some example values likedouble dn = 369.35,369.55.370.55
and size may be 0.05,0.10,0.5
etc...
if(((dn / size) % 1) == 0) {
Log.d(TAG,"OK");
} else {
Log.d(TAG,"OK");
}
请帮我把它短路.
推荐答案
(dn / size) % 1 == 0
虽然合理,但将遭受以二进制浮点运算为中心的陷阱.
(dn / size) % 1 == 0
whilst plausible, will suffer from pitfalls centred around binary floating point arithmetic.
如果您的数字始终不超过两位小数,那么最简单的方法是乘以100并按100 * y
除100 * x
的事实进行扩展,如果y
除以x
.换句话说:
If your numbers always have no more then two decimal places then the easiest thing to do is scale up by multiplying by 100 and rely on the fact that 100 * y
divides 100 * x
if y
divides x
. In other words:
if (Math.round(100 * dn) % Math.round(100 * size) == 0){
Log.d(TAG,"Divisible");
} else {
Log.d(TAG,"Not divisible");
}
这消除了二进制浮点算术的所有问题.我再次使用Math.round
而不是故意使用截断符来消除浮点周围的问题,并且依靠我认为该平台的怪癖,因为round
返回整数类型.
This obviates any issues with binary floating point arithmetic. I've used Math.round
rather than a truncation deliberately, again to obviate issues around floating point and am relying on what is in my opinion a quirk of this platform in that round
returns an integral type.
进一步阅读:浮点数学运算是否被破坏?
这篇关于Android除数(带小数部分)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!