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 integer
  • o: octal integer
  • e: floating-point in scientific notation
Answer from Anthony Forloney on Stack Overflow
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › Format-double-Java-printf-example
How to format a Java double with printf example
It is a common requirement to format currencies to two decimal places. You can easily achieve this with the Java printf function. Just use %.2f as the format specifier.
Discussions

Rounding two decimal places using Printf
Look up printf format strings (possibly in C, the syntax is the same). More on reddit.com
🌐 r/learnprogramming
5
1
September 22, 2015
Using printf to round 49.765 to 49.77? - Unix & Linux Stack Exchange
Notice that there are three different ... decimal places), rounded to nearest, and round up. Usually, you want round to nearest. As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close. ... Capture the output of the "ring of commands" in a variable and use printf... More on unix.stackexchange.com
🌐 unix.stackexchange.com
October 1, 2016
What does formatted output mean in java? In what situations is printf used?
It is basically used to provide more configurability to your output. For example, if you want to print out this: Val 1 = 10 Val 2 = 1 Val 3 = 100 (Edit: the code format didn't seem to make the characters the same size, so I had to add extra spaces for alignment in reddit specifically) With the 10, 1, and 100 being from variables, how would you line them up? You could do complex logic that figures out the length of the number, then prints an appropriate number of spaces. Or you can just use printf and use the format string "Val %d = %5d". The %5d says "print an integer (d) that takes up at least five spaces (5)", so this means no matter how long the actual number is, it will pad extra spaces to make it take up at least five (though it it has more than five digits, then you meed to reevaluate the amount of padding you use). Similarly, you can also make the int appear in Hex, or have zeroes padded in front in spaces, have a floating point print with a certain number of decimal places (so 0.541 can be printed as 0.54 by using %.2f, with ".2" meaning "to two decimal places).n Edit: In use, my example might look something like this: System.out.printf("Val %d = %5d\n", i, vars[i]); More on reddit.com
🌐 r/learnprogramming
3
1
January 10, 2022
Print exact value of double
I put together an example for you that prints the raw storage bits. I think it covers most cases and should print the stored value as close as possible. For 0.3 it prints 0.29999999999999998889776975374843450 value = 0.3 encoded1 = (5404319552844595 / 4503599627370496) * 2^-2 encoded2 = 1.199999999999999955591079014993738 * 2^-2 result = 0.29999999999999998889776975374843450 import java.math.BigDecimal; import java.math.MathContext; public class DoublePrinter { public static void main(String[] args) { // see https://en.wikipedia.org/wiki/Double-precision_floating-point_format // a double is stored as sign * significand * 2^(exp-1023) double value = 0.3; long bits = Double.doubleToLongBits(value); // the sign is stored in the upmost bit, same as long long sign = Long.signum(bits); // first bit long exponentBits = (bits & EXP_BIT_MASK) >>> 52; // next 11 bits long significandBits = bits & SIGNIF_BIT_MASK; // lowest 52 // add the implicit leading bit if not subnormal if (exponentBits != 0) { significandBits |= 0x10000000000000L; } // map to a more readable represenation (significand is stored as (value / 1L<<52)) long divisor = 1L << 52; int exponent = (int) (exponentBits - 1023); // compute result using BigDecimal var mc = MathContext.DECIMAL128; BigDecimal significand = new BigDecimal(significandBits).divide(new BigDecimal(divisor), mc); BigDecimal scale = new BigDecimal(2).pow(exponent, mc); BigDecimal result = new BigDecimal(sign).multiply(significand).multiply(scale); System.out.println("value = " + value); System.out.println(String.format("encoded1 = %s(%d / %d) * 2^%d", sign < 0 ? "-" : "", significandBits, divisor, exponent)); System.out.println(String.format("encoded2 = %s%s * 2^%d", sign < 0 ? "-" : "", significand.toString(), exponent)); System.out.println("result = " + result); } final static long SIGN_BIT_MASK = 0x8000000000000000L; final static long EXP_BIT_MASK = 0x7FF0000000000000L; final static long SIGNIF_BIT_MASK = 0x000FFFFFFFFFFFFFL; } More on reddit.com
🌐 r/javahelp
16
3
January 7, 2024
🌐
Oxford University
mathcenter.oxford.emory.edu › site › cs170 › printf
The printf Method
Interestingly, it is possible to creatively use casting and promotion to print a "double" value with only two decimal places. For example, we might do something similar to the following: double x = 12.345678; System.out.println("Number is approximately " + (int) (x * 100) / 100.0); But this seems a bit "kludgy". Java provides a better way to do the same thing with the "printf" method: double x = 12.345678; System.out.printf("Number is approximately %.2f", x); //prints "Number is approximately 12.35" System.out.printf( format, item1, item2, ..., itemK ); Here, "format" is a string to print with "format specifiers" (each consisting of a percent sign and a conversion code) that tell Java where and how to display "item1", "item2", etc...
🌐
Oracle
docs.oracle.com › javase › tutorial › java › data › numberformat.html
Formatting Numeric Print Output (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)
There are many converters, flags, and specifiers, which are documented in java.util.Formatter ... The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character. The output is: ... The printf and format methods are overloaded.
🌐
W3Schools
w3schools.com › java › ref_output_printf.asp
Java Output printf() Method
A . followed by a whole number indicating how many decimal digits to show in the formatted data. conversion - Required. A character which indicates how an argument's data should be represented. If the character is uppercase the data will be formatted in uppercase where possible. The list of possible characters is shown in the table below. ... // Default System.out.printf("%f%n", 123456.78); // Two decimal digits System.out.printf("%.2f%n", 123456.78); // No decimal digits System.out.printf("%.0f%n", 123456.78); // No decimal digits but keep the decimal point System.out.printf("%#.0f%n", 123456.78); // Group digits System.out.printf("%,.2f%n", 123456.78); // Scientific notation with two digits of precision System.out.printf("%.2e", 123456.78);
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-printf-method
Java printf() - Print Formatted String to Console | DigitalOcean
August 3, 2022 - jshell> float y = 2.28f y ==> 2.28 jshell> System.out.printf("Precision formatting upto 4 decimal places %.4f\n",y) Precision formatting upto 4 decimal places 2.2800 jshell> float z = 3.147293165f z ==> 3.147293 jshell> System.out.printf("Precision formatting upto 2 decimal places %.2f\n",z) Precision formatting upto 2 decimal places 3.15 ·
🌐
iCert Global
icertglobal.com › home › community › how can i format a float to exactly 2 decimal places in java for financial reporting?
How can I format a float to exactly 2 decimal places in Java for financial reporting? | iCert Global
If he uses DecimalFormat, he should probably define it like new DecimalFormat("0.00"). This ensures that even if the number is less than one, like .50, it displays as "0.50" rather than just ".50". It’s a small detail but makes a huge difference in professional software development and data readability. ... For a quick fix, System.out.format("%.2f", myFloat); works exactly like printf and is very easy to implement without importing extra libraries.
Find elsewhere
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › Java-double-precision-2-decimal-places-example-float-range-math-jvm
Java double decimal precision
The precision of a double in Java is 10-324 decimal places, although true mathematical precision can suffer due to issues with binary arithmetic. To simplify display, you can use %d printf notation to format a Java double’s precision to two ...
🌐
CodeGym
codegym.cc › java blog › strings in java › printf() in java
Printf() in Java
December 23, 2024 - The value of pi with 3 decimal places is: 3.142 Here we use the printf() method to format and display the value of pi with a specific number of decimal places. The format specifier %.3f indicates that we want to display the floating-point number ...
🌐
Reddit
reddit.com › r/learnprogramming › rounding two decimal places using printf
r/learnprogramming on Reddit: Rounding two decimal places using Printf
September 22, 2015 -

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.

🌐
Medium
naveenautomationlabs.medium.com › mastering-system-out-printf-in-java-dcab1af7dd27
Mastering System.out.printf() in Java | by Naveen AutomationLabs | Medium
April 26, 2025 - Reuse previous argument with < flag int n = 123; System.out.printf("20. Hex: %1$x, Decimal: %<d%n", n); // 21. Loop example System.out.println("21. Table:"); for (int i = 1; i <= 5; i++) { System.out.printf(" %d squared is %d%n", i, i * i); } } } 1. The number is: 42 2. Pi to 2 decimal places: 3.14 3.
🌐
Baeldung
baeldung.com › home › java › java numbers › number formatting in java
Number Formatting in Java | Baeldung
August 9, 2024 - In Java, we have two primitive types that represent decimal numbers, float and decimal: double myDouble = 7.8723d; float myFloat = 7.8723f; The number of decimal places can be different depending on the operations being performed. In most cases, we’re only interested in the first couple of decimal places.
🌐
Stack Overflow
stackoverflow.com › a › 37034123
Printing the correct amount of decimal places? (printf) - JAVA - Stack Overflow
public static void main(String[] args) { double x = 100.512f; //no decimal places if (x % 1 == 0) { System.out.printf("x = %.0f", (float) x); //one decimal place } else if ((x * 10) % 1 == 0) { System.out.printf("x = %.1f", (float) x); //two ...
Top answer
1 of 3
6
$ x=49.765
$ printf "%.2f" $(echo "$x + 0.005" | bc)

You have to use external commands because there is no built-in rounding feature in printf(1), and the POSIX shell doesn't have built-in floating-point arithmetic.

To round to the nearest decimal digit, you add 0.5 and truncate. To round to the nearest tenth, you divide the "nudge factor" by 10, and so forth.

This lack of built-in facilities is what often pushes people to use something like Perl rather than shell:

$ perl -e 'printf "%.2f", 49.765 + 0.005'

Same thing, but all handled by a single process.

2 of 3
0

You can use following command for rounding off.

float number = 49.765; printf("%0.2f", number);

You should be able to get the 2 figures after decimal point.

But this will just print, it will not update the value. If you would like to change the value of the variable then you should use below.

#include <math.h>

float val = 49.765;

float rounded_down = floorf(val * 100) / 100;   /* Result: 49.76 */
float nearest = roundf(val * 100) / 100;  /* Result: 49.77 */
float rounded_up = ceilf(val * 100) / 100;      /* Result: 49.77 */

Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.

As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.

🌐
LabEx
labex.io › tutorials › java-formatting-with-printf-117408
Formatting with Printf in Java | LabEx
javac project_formatting_printf.java java project_formatting_printf ... To format decimals, use the %f format specifier. For example: public static void main(String[] args) { double num = 3.14159265359; System.out.printf("The number is: %.2f%n", ...
🌐
Coderanch
coderanch.com › t › 721637 › java
%.2f\n (Beginning Java forum at Coderanch)
November 8, 2019 - 1: Use a BigDecimal and a MathContext object to round all the calculations to 2DP; that will actually work in decimal places. 2: What you are probably doing viz. displaying the result rounded to 2DP. That only rounds the display, not the calculation.I would do something like this:If you print ...
🌐
JanBask Training
janbasktraining.com › community › java › format-double-2-decimal-places-in-java
How can we display an output of float data with 2 decimal ...
July 26, 2021 - The %.2f syntax tells Java to return your variable (value) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
🌐
Medium
medium.com › @sitharawanigasooriya_ › mastering-output-formatting-in-java-using-printf-78b2255ad6ef
Mastering Output Formatting in Java Using printf | by Sithara Wanigasooriya | Medium
November 16, 2024 - System.out.printf("%.2f", 3.14159); // Output: 3.14 · %.2f rounds to 2 decimal places. System.out.printf("%s", "Hello, World!"); // Output: Hello, World! Outputs the string as is.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-set-precision-for-double-values-in-java
How to Set Precision For Double Values in Java? - GeeksforGeeks
July 12, 2025 - // Demonstrating the precision modifier import java.util.*; class GFG { public static void main (String[] args) { Formatter fm=new Formatter(); // Format 4 decimal places fm.format("%.4f", 123.1234567); System.out.println(fm); fm.close(); //Format 2 decimal places in a 16 character field fm=new Formatter(); fm.format(".2e",123.1234567); System.out.println("GFG!"); fm.close(); //Display atmost 15 characters in a string fm=new Formatter(); fm.format("%.15s", "Learning with Gfg is easy quick"); System.out.println(fm); fm.close(); } }