// floating point calculationfinal double amount1 = 2.0;final double amount2 = 1.1;System.out.println("difference between 2.0 and 1.1 using double is: " + (amount1 - amount2));
// Use BigDecimal for financial calculationfinal BigDecimal amount3 = new BigDecimal("2.0");final BigDecimal amount4 = new BigDecimal("1.1");System.out.println("difference between 2.0 and 1.1 using BigDecimal is: " + (amount3.subtract(amount4)));
输出:
difference between 2.0 and 1.1 using double is: 0.8999999999999999difference between 2.0 and 1.1 using BigDecimal is: 0.9
double total = 0.0;
// adds 10 cents, 10 timesfor (int i = 0; i < 10; i++) {total += 0.1; // adds 10 cents}
Log.d("result: ", "current total: " + total);
// looks like total equals to 1.0, don't?
// now, do reversefor (int i = 0; i < 10; i++) {total -= 0.1; // removes 10 cents}
// total should be equals to 0.0, right?Log.d("result: ", "current total: " + total);if (total == 0.0) {Log.d("result: ", "is total equal to ZERO? YES, of course!!");} else {Log.d("result: ", "is total equal to ZERO? No...");// so be careful comparing equality in this cases!!!}
输出:
result: current total: 0.9999999999999999result: current total: 2.7755575615628914E-17 🤔result: is total equal to ZERO? No... 😌
// create a monetary valueMoney money = Money.parse("USD 23.87");
// add another amount with safe double conversionCurrencyUnit usd = CurrencyUnit.of("USD");money = money.plus(Money.of(usd, 12.43d));
// subtracts an amount in dollarsmoney = money.minusMajor(2);
// multiplies by 3.5 with roundingmoney = money.multipliedBy(3.5d, RoundingMode.DOWN);
// compare two amountsboolean bigAmount = money.isGreaterThan(dailyWage);
// convert to GBP using a supplied rateBigDecimal conversionRate = ...; // obtained from code outside Joda-MoneyMoney moneyGBP = money.convertedTo(CurrencyUnit.GBP, conversionRate, RoundingMode.HALF_UP);
// use a BigMoney for more complex calculations where scale mattersBigMoney moneyCalc = money.toBigMoney();