java 中 Integer 跟 double类型相乘还有比较的问题
今早遇到了一个问题?Integer 跟 double类型相乘的问题
eg1:
Integer packSize = 2;Integer qty = 7;Double nw = 20.4;int result = qty - qty % packSize;System.out.println(qty % packSize);System.out.println(qty - qty % packSize);System.out.println(nw * result);
?输出结果:
6122.39999999999999?
?
eg2:
Integer packSize = 2;Integer qty = 7;Double nw = <font color="#FF0000">20.5</font>;int result = qty - qty % packSize;System.out.println(qty % packSize);System.out.println(qty - qty % packSize);System.out.println((float)nw * result);?
输出结果:
6122.4
?
然后我选者了BigDecimal
?
eg:
public static void main(String arg[]){ BigDecimal bd = new BigDecimal("0"); bd = bd.add(new BigDecimal("99.99")); bd = bd.add(new BigDecimal("1.99")); System.out.println("BigDecimal result " + bd); double d = 99.99; d = d + 1.99; System.out.println("Double result " + d);}
输出结果为:
BigDecimal result 101.98Double result 101.97999999999999?
然后我这样做的:
Double grossWeight;//.....@Transient??? public Integer getRemainder() {??? ??? return qty % packSize;??? }?@Transient public Double getGrossWeights() { return grossWeight * getRemainder(); }?
因为我上一级要做加法运算
@Transientpublic Double getTotalGrossWeightAmount() {class EntrySubTotalVisitor implements Visitor<ShipmentRecordEntry> {Double totalGrossWeightAmount = 0.0;public void visit(final ShipmentRecordEntry entry) {totalGrossWeightAmount += entry.getGrossWeights();}}EntrySubTotalVisitor visitor = new EntrySubTotalVisitor();Algorithms.traverse(shipmentRecordEntries, visitor);return visitor.totalGrossWeightAmount;}
?so:
?
我的测试是这样写的
?
import org.testng.annotations.Test;import java.math.BigDecimal;@Testpublic void testGetGrossWeights() {ShipmentRecordEntry entry = new ShipmentRecordEntry();entry.setQty(7);entry.setPackSize(2);entry.setGrossWeight(20.4);BigDecimal bd = new BigDecimal(entry.getGrossWeights());assert String.valueOf(bd.floatValue()).equals("122.4") : String.valueOf(bd.floatValue());}?
测试pass。
?