Java 中判断双Double数是否整除
2019-05-15 本文已影响0人
丶晓虎
在java中,对于大于1的数A和B且A大于B的情况下,直接使用A%B==0可以判断A是否是B的倍数,即A可以被B整除,但是如果是小数的情况下,则方法可能不是100%有效,就拿0.08来说,经过几次测试,0.16,0.32都没问题,唯独0.24取余竟然是0.079999999,不论在Java还是Js都是一个毛病,索性换算成整数来判断。
粗略的代码,记录下,可能有改进的地方
Java代码
/**
* 判断是否倍数或整除
* @param x 大值
* @param y 小值
* @return 结果
* @date 2019年5月15日
*/
public static boolean isPositiveIntegerTimes(Double x, Double y) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
if (x < y || x == y) {
return false;
}
Integer newX = 1;
Integer newY = 1;
if (x <= 1 && y < 1) {
int t1 = x.toString().split("\\.")[1].length();
int t2 = y.toString().split("\\.")[1].length();
int pInt = 1;
if (t1 > t2) {
pInt = t1;
}
else if (t1 < t2) {
pInt = t2;
}
else {
pInt = t1;
}
Double powNum = Math.pow(10, pInt);
Double xNum = powNum * x;
Double yNum = powNum * y;
// 同乘相同倍数
newX = xNum.intValue();
newY = yNum.intValue();
}
else if (x >= 1 && y < 1) {
if (x % 1 == 0) {
newX = x.intValue();
System.err.println("目标数检测到整数:" + x);
}
if (y % 1 == 0) {
newY = y.intValue();
System.err.println("来源数检测到整数:" + y);
}
int t1 = x.toString().split("\\.")[1].length();
int t2 = y.toString().split("\\.")[1].length();
int pInt = 1;
if (t1 > t2) {
pInt = t1;
}
else if (t1 < t2) {
pInt = t2;
}
else {
pInt = t1;
}
Double powNum = Math.pow(10, pInt);
Double xNum = powNum * x;
Double yNum = powNum * y;
// 同乘相同倍数
newX = xNum.intValue();
newY = yNum.intValue();
}
else if (x >= 1 && y >= 1) {
if (pattern.matcher(x.toString()).matches()) {
newX = x.intValue();
System.err.println("目标数检测到整数:" + x);
}
if (pattern.matcher(y.toString()).matches()) {
newY = y.intValue();
System.err.println("来源数检测到整数:" + y);
}
int t1 = x.toString().split("\\.")[1].length();
int t2 = y.toString().split("\\.")[1].length();
int pInt = 1;
if (t1 > t2) {
pInt = t1;
}
else if (t1 < t2) {
pInt = t2;
}
else {
pInt = t1;
}
Double powNum = Math.pow(10, pInt);
Double xNum = powNum * x;
Double yNum = powNum * y;
// 同乘相同倍数
newX = xNum.intValue();
newY = yNum.intValue();
}
if (newX % 1 == 0 && newY % 1 == 0) {
if (newX % newY == 0) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
Js代码
function isPositiveIntegerTimes(x,y){
if (x < y || x == y) {
return false;
}
var newX = 0;
var newY = 0;
if (x < 1 && y < 1) {
var t1 = x.toString().split(".")[1].length;
var t2 = y.toString().split(".")[1].length;
var pInt = 1;
if (t1 > t2) {
pInt = t1;
}
else if (t1 < t2) {
pInt = t2;
}
else {
pInt = t1;
}
var powNum = Math.pow(10, pInt);
var xNum = powNum * x;
var yNum = powNum * y;
// 同乘相同倍数
newX = Math.ceil(xNum);
newY = Math.ceil(yNum);
}
else if (x >= 1 && y >= 1) {
newX = Math.ceil(x);
newY = Math.ceil(y);
}
if (newX % newY == 0) {
return true;
}
else {
return false;
}
}