You can use the printf method, like so:
System.out.printf("%.2f", val);
In short, the %.2f syntax tells Java to return your variable (val) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
There are other conversion characters you can use besides f:
d: decimal integero: octal integere: floating-point in scientific notation
You can use the printf method, like so:
System.out.printf("%.2f", val);
In short, the %.2f syntax tells Java to return your variable (val) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
There are other conversion characters you can use besides f:
d: decimal integero: octal integere: floating-point in scientific notation
You can use DecimalFormat. One way to use it:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));
Another one is to construct it using the #.## format.
I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.
java - printf %f with only 2 numbers after the decimal point? - Stack Overflow
Rounding two decimal places using Printf
[Grade 11: Computer Science (java)] I need to figure out how to get exactly 2 digits for cents (i.e. $12.5 must be $12.50). However, this must be done with all math and no built-in functions. Any suggestions to improve my code would also be helpful, thanks.
printf - Java - How to print values to 2 decimal places - Stack Overflow
Videos
Use this:
printf ("%.2f", 3.14159);
You can use something like this:
printf("%.2f", number);
If you need to use the string for something other than printing out, use the NumberFormat class:
NumberFormat formatter = new DecimalFormatter("#.##");
String s = formatter.format(3.14159265); // Creates a string containing "3.14"
Hey guys, so I was just about to finish task one of my programming project when I realized that I needed to stop the ending number at 2 decimal places.
My professor does not wanting us using methods we have not learned yet, and he said that we could use PrintF, however we did not have to use PrintF.
Here is my code that is currently operational:
import java.util.Scanner;
public class A1 {
public static void main(String[] args)
{
int ValueOne;
int ValueTwo;
int ValueThree;
float Average;
Scanner in = new Scanner(System.in);
System.out.println("Enter first value: ");
ValueOne = in.nextInt();
System.out.println("You have entered int: "+ValueOne);
System.out.println("Enter second value: ");
ValueTwo = in.nextInt();
System.out.println("You have entered int: "+ValueTwo);
System.out.println("Enter third value: ");
ValueThree = in.nextInt();
System.out.println("You have entered int: "+ValueThree);
System.out.printf("The average of your three value is : " + ((ValueOne + ValueTwo + ValueThree) /3));
}}
I tried researching it before I came here, however did not find anything using PrintF. Any help is greatly appreciated thanks.
You have misunderstood the printf method. You do not concatenate strings the way you do in this line and its successors (reformatted for width reasons):
System.out.printf("Home team is:" + homeName +
" from" + homeLocation +
" rated" + homeTeam.offense +
" (offense) +" + homeTeam.defense +
" (defense)" + "\n");
This is like the way an old coworker tried to use PreparedStatements to prevent SQL injection attacks, but constructed the query string by concatenation anyway, making the attempt ineffective. Instead, look at the signature of printf:
public PrintWriter format(String format, Object... args)
The first argument is a format string, which contains static text and format directives beginning with %. In typical use, each format directive corresponds to one argument of the method. Replace the interpolated variables with directives.
Strings are usually formatted with %s: s for string. Doubles are usually formatted with %f: f for float (or double). Characters between the % and the letter are options. So, let's replace the strings you interpolated with directives:
"Home team is: " + "%s" + // Inserted a space.
" from" + "%s" +
" rated" + "%6.2f" + // Six characters, 2 after the decimal.
" (offense) +" + "%6.2f" +
" (defense)" + "%n" // %n means the appropriate way to get a new line
// for the encoding.
Now we put it all together:
System.out.format("Home team is: %s from %s rated %6.2f (offense) + %6.2f (defense)%n",
homeName, homeLocation, homeTeam.offense, homeTeam.defense);
This is a lot simpler. Additionally, another reason to avoid interpolating strings in a format string is that the strings you interpolate may contain a percent sign itself. See what happens if you unguardedly write this:
String salesTax = "5%";
System.out.format("The sales tax is " + salesTax);
That's equivalent to
System.out.format("The sales tax is 5%");
Unfortunately, the percent sign is treated as a format directive, and the format statement throws an exception. Correct is either:
System.out.format("The sales tax is 5%%");
or
String salesTax = "5%";
System.out.format("The sales tax is %s", salesTax);
But now I should ask why you did not take homeName and homeLocation from Team. Certainly they are more relevant to Team than to each other. In fact, you should look up the Formattable interface, and with proper coding you can write:
System.out.format("%s%, homeTeam);
Try this:
public class A {
public static void main(String[] args) {
System.out.println(String.format("%.2f", 12.34123123));
}
}