The NumberFormat and DecimalFormat classes provide support for parsing and formatting currency values.
For example to parse a string containing a money value in the default locale you can use the following.
NumberFormat format = NumberFormat.getCurrencyInstance();
Object value = format.parse("$5.45");
written by objects
\\ tags: Currency, DecimalFormat, Locale, money, NumberFormat, parse
The NumberFormat class provides support for currency formatting. By current default Locale is used to determine what currency the value should be formatted in.
double value = 6.34;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String formatted = formatter.format(value);
written by objects
\\ tags: Currency, format, money, NumberFormat
Following shows how to use a loop to determine the breakdown of change for a given amount, minimising the number of notes and coins used.
int[] denominations = { 500, 200, 100, 50, 20, 10, 5, 2, 1 };
int amount = 687;
int[] count = new int[denominations.length];
for (int i=0; i<denominations.length; i++) {
while (amount>=denominations[i]) {
count[i]++;
amount -= denominations[i];
}
}
System.out.println(Arrays.toString(count));
written by objects
\\ tags: array, change, Currency, loop