有没有一种方法可以比较(>,<,> =,< =,!=,==)十进制表示为long和int?
如果数字是3214.21那么它将在类似
的类中表示long units = 321421;
int precision = 2;
// to get the original number I would do units * 10^precision
我希望能够做一些类似于BigDecimal的compareTo()方法。因此大于返回1,等于返回0,小于返回-1。
我目前正在做的事情在某些情况下不起作用。导致它以这种方式运行的代码概述如下。该方法或多或少是概念证明。
public int compareTo(Money other) {
if (precision == other.getPrecision()) { // fast check if precision is the same
if (units > other.getUnits()) return 1; // we forgot to inverse/flip here. will be an issue for non-decimal
else if (units < other.getUnits()) return -1;
else return 0; // least likely
}
int intX = (int) (units / (Math.pow(10, precision))); // converted units whole numbers to int
int fractionX = (int) (units % (Math.pow(10, precision))); // converts the decimal as an int
int intY = (int) (other.getUnits() / (Math.pow(10, other.getPrecision()))); // converted units whole numbers to int
int fractionY = (int) (other.getUnits() % (Math.pow(10, other.getPrecision()))); // converts the decimal as an int
System.out.println("Test: i " + intX + "| f " + fractionX + "| u " + units + "| p " + precision);
System.out.println("Test2: i " + intY + "| f " + fractionY + "| u " + other.getUnits() + "| p" + other
.getPrecision
());
if (intX > intY) return 1;
else if (intX < intY) return -1;
else {
if (fractionX > fractionY) return 1; // this is where the logic fails
if (fractionX < fractionY) return -1;
else return 0;
}
}
这是我的测试以及输出
System.out.println(MoneyFactory.fromString("0.3").compareTo(MoneyFactory.fromString("0.29")));
System.out.println(MoneyFactory.fromString("13").compareTo(MoneyFactory.fromString("0.31456789")));
System.out.println(MoneyFactory.fromString("0.2999").compareTo(MoneyFactory.fromString
("0.3")));
输出
Test: i 0| f 3| u 3| p 1
Test2: i 0| f 29| u 29| p2
-1
Test: i 13| f 0| u 13| p 0
Test2: i 0| f 31456789| u 31456789| p8
1
Test: i 0| f 2999| u 2999| p 4
Test2: i 0| f 3| u 3| p1
1
答案 0 :(得分:1)
最简单的解决方案是将一个数字转换为通用精度级别,然后比较数字。如果它们是相同的那么使用具有更高精度的数字&#39;逻辑(伪代码):
return (number1 == number2) ? [number with bigger precision logic] : number1 - number2
在Java代码中
class Money {
long units;
int precision;
public Money (long un, int prec) {
units = un;
precision = prec;
}
public int compareTo(Money other) {
int preResult = this.precision - other.precision;
long first = (preResult > 0) ? ((long)(this.units / Math.pow(10, preResult))) : this.units;
long second = (preResult < 0) ? ((long)(other.units * Math.pow(10, preResult))) : other.units;
return (first == second) ? preResult : Long.compare(first, second);
}
public static void test() {
Money first = new Money(2345L, 4);
Money second = new Money(234567L, 6);
System.out.println(first.compareTo(second));
}
}
编辑:代码中有错误。将两个tenary支票中的1更改为0可解决此问题
答案 1 :(得分:0)
我想你只是这样做:
public int compareTo(Money other) {
return Double.compare(units/Math.pow(10, precision), other.getUnits()/Math.pow(10, other.getPrecision()));
}