Skip to content

Instantly share code, notes, and snippets.

@soeirosantos
Last active November 3, 2016 14:38
Show Gist options
  • Save soeirosantos/d707ea7291e58db7a8dd9071e1c8dea2 to your computer and use it in GitHub Desktop.
Save soeirosantos/d707ea7291e58db7a8dd9071e1c8dea2 to your computer and use it in GitHub Desktop.
About BigDecimal
double fixedCost = 0.1;
double variableCost = 0.7;
double totalCost = fixedCost + variableCost;
System.out.println(totalCost);
//output: 0.7999999999999999
BigDecimal calculatedRate = calculatedRate.setScale(1, RoundingMode.HALF_UP);
System.out.println(expectedRate.compareTo(calculatedRate) == 0);
//output: true
BigDecimal fixedCost = new BigDecimal(0.1);
BigDecimal variableCost = new BigDecimal(0.7);
BigDecimal totalCost = fixedCost.add(variableCost);
System.out.println(totalCost);
//output: 0.7999999999999999611421941381195210851728916168212890625
BigDecimal fixedCost = new BigDecimal("0.1");
BigDecimal variableCost = new BigDecimal("0.7");
BigDecimal totalCost = fixedCost.add(variableCost);
System.out.println(totalCost);
//output: 0.8
BigDecimal totalSalesTwoMonths = new BigDecimal("100.0");
BigDecimal twoMonths = new BigDecimal("2");
BigDecimal avgSalesTwoMonths = totalSalesTwoMonths.divide(twoMonths);
System.out.println(avgSalesTwoMonths);
//output: 50.0
BigDecimal totalSalesQuarter = new BigDecimal("100.0");
BigDecimal threeMonths = new BigDecimal("3");
BigDecimal avgQuarter = totalSalesQuarter.divide(threeMonths);
//output: java.lang.ArithmeticException: Non-terminating decimal expansion;
//no exact representable decimal result.
BigDecimal avgQuarter = totalSalesQuarter.divide(threeMonths, RoundingMode.HALF_UP);
System.out.println(avgQuarter);
//output: 33.3
//think this "0.0" value came from screen
BigDecimal loss = new BigDecimal("0.0");
//And now I need to check if loss in the month was zero
System.out.println(loss.equals(BigDecimal.ZERO));
//output: false
System.out.println(loss.compareTo(BigDecimal.ZERO) == 0);
//output: true
BigDecimal expectedRate = new BigDecimal("15.5");
BigDecimal calculatedRate = new BigDecimal("15.5178");
System.out.println(expectedRate.compareTo(calculatedRate) == 0);
//output: false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment