0

I have been trying to print this out:

System.out.println("Year " + (2021 + j) + " you can buy " + ((int)(budget / total)) + " " +
        itemName + "s");

I'm supposed to only print out 2 decimals spaces and it's printing out many more than that. How can I fix this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

3 Answers3

1

Have a look at this website about string format specifiers. What you can do is use the String.format function, which returns a String and will let you specify how many decimal places you want to print out. In your case, that might look like:

String outputString = String.format("Year %d you can buy %.2f %ss", (2021 + j), (budget / total), itemName);
System.out.println(outputString);

The %.2f indicates that the corresponding argument should be printed as a floating point number and be rounded to two decimal places.

fireshadow52
  • 6,298
  • 2
  • 30
  • 46
0

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.

ioannis-kokkalis
  • 432
  • 1
  • 3
  • 13
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/31618258) – ShockwaveNN Apr 25 '22 at 12:23
  • 1
    @ShockwaveNN thanks for the review. It must be improved now. – ioannis-kokkalis Apr 25 '22 at 13:24
-1

I haven't used java but you could do something like this

public class Main {

    public static void main(String[] args) {
        float a = 30;
        float b = 6.5f;

        float answer1 = a / b;
        //Value is 4.6153846

        System.out.println(answer1);

        float answer2 = (float) (Math.floor((a / b) * 100)) / 100;
        //Multiplied 4.6153846 by 100 to 461.53846
        //Floored it to 461
        //Then divided it by 100
        System.out.println(answer2);

    }
}

Console:

4.6153846

4.61
Kirby
  • 15,127
  • 10
  • 89
  • 104
1WeirdDev
  • 11
  • 1