Skip to content

Commit

Permalink
fix(计算工具): 修复float与int计算精度丢失问题
Browse files Browse the repository at this point in the history
  • Loading branch information
bestfeng1020 committed Aug 13, 2024
1 parent c5cc9fe commit 6e60584
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
31 changes: 26 additions & 5 deletions src/main/java/org/jetlinks/reactor/ql/utils/CalculateUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,17 @@ public static <T> T calculate(Number left,
if (right instanceof BigInteger) {
return calculate((BigInteger) right, left, (r, l) -> opsForInteger.apply(l, r));
}
if(left instanceof Float && right instanceof Float){
return opsForFloat.apply(left.floatValue(), right.floatValue());
}
if (left instanceof Float || right instanceof Float ||
left instanceof Double || right instanceof Double) {
if (left instanceof Double || right instanceof Double){
return opsForDouble.apply(left.doubleValue(), right.doubleValue());
}
if (left instanceof Float){
return calculate((Float) left, right, opsForFloat, opsForDouble);
}
if (right instanceof Float){
return calculate((Float) right, left,
(r, l) -> opsForFloat.apply(l, r),
(r, l) -> opsForDouble.apply(l, r));
}
return opsForLong.apply(left.longValue(), right.longValue());
}

Expand All @@ -163,6 +167,15 @@ public static <T> T calculate(BigDecimal left, Number right,
if (right instanceof BigInteger) {
return ops.apply(left, new BigDecimal((BigInteger) right));
}
if (right instanceof Float){
return ops.apply(left, BigDecimal.valueOf(right.floatValue()));
}
if (right instanceof Integer){
return ops.apply(left, BigDecimal.valueOf(right.intValue()));
}
if (right instanceof Long){
return ops.apply(left, BigDecimal.valueOf(right.longValue()));
}
return ops.apply(left, BigDecimal.valueOf(right.doubleValue()));
}

Expand All @@ -177,5 +190,13 @@ public static <T> T calculate(BigInteger left, Number right,
return ops.apply(left, BigInteger.valueOf(right.longValue()));
}

public static <T> T calculate(Float left, Number right,
BiFunction<Float, Float, T> opsForFloat,
BiFunction<Double, Double, T> opsForFloatDouble) {
if (right instanceof Float || right instanceof Integer) {
return opsForFloat.apply(left, right.floatValue());
}
return opsForFloatDouble.apply(left.doubleValue(), right.doubleValue());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ void testSub() {
@Test
void testMultiply() {

assertEquals(CalculateUtils.multiply(2.1F, 10), 21F);
assertEquals(CalculateUtils.multiply(2, 1), 2L);
assertEquals(CalculateUtils.multiply(2F, 1F), 2F);
assertEquals(CalculateUtils.multiply(2D, 1F), 2D);
Expand Down

0 comments on commit 6e60584

Please sign in to comment.