问题
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 like
double 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");
}
please help me to short out it.
回答1:
(dn / size) % 1 == 0
whilst plausible, will suffer from pitfalls centred around binary floating point arithmetic.
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");
}
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.
Further reading: Is floating point math broken?
回答2:
You are doing it wrongly,
try with this code
if(dn % size == 0) {
Log.d(TAG,"Divisible");
} else {
Log.d(TAG,"Not divisible");
}
Update
Use BigDecimal in case you have big decimal numbers
eg :
BigDecimal bg1, bg2, bg3;
bg1 = new BigDecimal("513.54");
bg2 = new BigDecimal("5");
// bg2 divided by bg1 gives bg3 as remainder
bg3 = bg1.remainder(bg2);
来源:https://stackoverflow.com/questions/45142068/android-divide-number-with-decimal-fraction