Home > Software engineering >  Java - How to print out only a specific number after decimal
Java - How to print out only a specific number after decimal

Time:04-25

I have been trying to print this out:

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

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

CodePudding user response:

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.

CodePudding user response:

If you are familiar with printf you can use it instead of println.

Otherwise there is a method called format() for strings in Java. This is a good starting point to learn how to use it.

CodePudding user response:

i havent used java but you could do something like this

//Code

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

  • Related