General
If you are familiar with printf
you can use it instead of println
.
Otherwise there is a method called format()
for Java Strings. A generic example to get the idea:
double value = 2/3.0;
System.out.println("Original: " + value);
System.out.println(String.format("Formatted: %.2f", value));
Solution
For your situation the formatting would look something like this:
System.out.println("Year " + (2021 + j) + " you can buy " + String.format("%.2f", budget/total) + " " + itemName + "s");
%.Nf
keeps N
decimals of a double value
. That's why i removed the int typecast and assumed either budget or total variable will be type of double so the division returns a double value. If neither of those is double, int/int will return int value causing format()
to throw and Exception because it expects double type value as second arguement since first argument had f
in the way to format.
More
Here you can find more detailed information for the number formatting topic.