Created
June 21, 2017 04:33
-
-
Save anonymous/0d15f97c3f1b5ce4005531a7c41afdfc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package scrap.stackoverflow; | |
import java.math.BigDecimal; | |
import java.text.DecimalFormat; | |
public class CurrencyManstissa { | |
private static final DecimalFormat MONEY_FORMAT = new DecimalFormat("#,##0.00"); | |
private static final String STRING_FORMAT = "%s %5d %30s"; | |
private static final BigDecimal D100 = BigDecimal.valueOf(100); | |
/** | |
* Calculate the GDP table in jumps of 10 years for the given start value and growth rate. | |
* @param start starting GDP in dollars | |
* @param growthPct the growth rate (e.g., 3 = 3% growth) | |
* @param totalYears the number of years the table will cover | |
*/ | |
public static void makeGDPTable(double start, int growthPct, int totalYears) { | |
double startDouble = start * 100; | |
double growthDouble = (100 + growthPct) / 100.0; | |
BigDecimal startDecimal = BigDecimal.valueOf(start); | |
BigDecimal growthDecimal = BigDecimal.valueOf(100 + growthPct).divide(D100); | |
for (int year = 0; year < totalYears; year += 10) { | |
double gdpDouble = startDouble * Math.pow(growthDouble, year); | |
BigDecimal gdpDecimal = startDecimal.multiply(growthDecimal.pow(year)); | |
double delta = gdpDouble / 100 - gdpDecimal.doubleValue(); | |
System.out.println(String.format(STRING_FORMAT, "double ", year, "$ " + MONEY_FORMAT.format(gdpDouble / 100))); | |
System.out.print(String.format(STRING_FORMAT, "Decimal", year, "$ " + MONEY_FORMAT.format(gdpDecimal.doubleValue()))); | |
System.out.println(String.format(" (%.10f)", delta)); | |
} | |
} | |
public static void main(String[] args) { | |
makeGDPTable(1_000_000_000, 5, 200); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment