One of the way would be using NumberFormat.

NumberFormat formatter = new DecimalFormat("#0.00");     
System.out.println(formatter.format(4.0));

Output:

4.00

Answer from kosa on Stack Overflow
🌐
Mkyong
mkyong.com › home › java › how to format a double in java
How to format a double in Java - Mkyong.com
July 23, 2020 - This example uses DecimalFormat to format a double; it also supports locale. ... package com.mkyong.io.utils; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; public class FormatDouble2 { public static void main(String[] args) { DecimalFormat df = new DecimalFormat("#,###.##"); // different locale - GERMAN DecimalFormat dfGerman = new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.GERMAN)); String input = "1234567890.123456"; double d = Double.parseDouble(input); System.out.println(df.format(d)); // 1,234,567,890.12 System.out.println(dfGerman.format(d)); // 1.234.567.890,12 } }
🌐
Baeldung
baeldung.com › home › java › java numbers › number formatting in java
Number Formatting in Java | Baeldung
August 9, 2024 - In this tutorial, we’ll learn about the different approaches to number formatting in Java, and how to implement them. The String#format method is very useful for formatting numbers. The method takes two arguments. The first argument describes the pattern of how many decimals places we want to see, and the second argument is the given value: double value = 4.2352989244d; assertThat(String.format("%.2f", value)).isEqualTo("4.24"); assertThat(String.format("%.3f", value)).isEqualTo("4.235");
🌐
TutorialsPoint
tutorialspoint.com › format-double-type-in-java
Format double type in Java
public class Demo { public static void main(String args[]) { double val1 = 15.546; double val2 = 25.87; double val3 = Math.PI; System.out.format("%f%n", val1); System.out.printf("exp(%.3f) = %.3f%n", val1, Math.exp(val1)); System.out.printf("log = %.3f%n", val1, Math.log(val1)); System.out.format("?%n", val2); System.out.format("%+3f%n", val2); System.out.format("%f%n", val3); System.out.format("%.3f%n", val3); System.out.printf("pow(%.3f, %.3f) = %.3f%n", val1, val2, Math.pow(val1, val2)); } }
🌐
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
A double in Java is a 64-bit number, and the 64-bit precision of a double never changes within a Java program. However, to format the output of a double to two decimal places, simply use the printf method and %.2f as the specifier.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Double.html
Double (Java Platform SE 8 )
October 20, 2025 - The argument is considered to be ... "double format" bit layout. If the argument is 0x7ff0000000000000L, the result is positive infinity. If the argument is 0xfff0000000000000L, the result is negative infinity. If the argument is any value in the range 0x7ff0000000000001L through ...
🌐
W3Schools
w3schools.com › java › ref_string_format.asp
Java String format() Method
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. ... double myNumber = 123456.78; String result; // Default result = String.format("%f", myNumber); System.out.println(result); // Two decimal digits result = String.format("%.2f", myNumber); System.out.println(result); // No decimal digits result = String.format("%.0f", myNumber); System.out.println(result); // No decimal digits but keep the decimal point result = String.format("%#.0f", myNumber); System.out.println(result); // Group digits result = String.format("%,.2f", myNumber); System.out.println(result); // Scientific notation with two digits of precision result = String.format("%.2e", myNumber); System.out.println(result);
Find elsewhere
🌐
Oracle
docs.oracle.com › javase › tutorial › java › data › numberformat.html
Formatting Numeric Print Output (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)
Further detail can be found in the Basic I/O section of the Essential trail, in the "Formatting" page. Using String.format to create strings is covered in Strings. You can use the java.text.DecimalFormat class to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator.
🌐
Apache Commons
commons.apache.org › proper › commons-text › apidocs › org › apache › commons › text › numbers › DoubleFormat.html
DoubleFormat (Apache Commons Text 1.14.0 API)
This type is intended to provide ... double format functions for common format types using a builder pattern. Output can be localized by passing a DecimalFormatSymbols instance to the formatSymbols method or by directly calling the various other builder configuration methods, such as digits.
🌐
Edureka Community
edureka.co › home › community › categories › java › formatting double value in java
Formatting Double Value in Java | Edureka Community
May 15, 2018 - I am dealing with lot of double values in my application, is there is any easy way to handle the formatting of ... to 35.70 3.0 to 3.00 9 to 9.00
🌐
Mkyong
mkyong.com › home › java › java – display double in 2 decimal places
Java - Display double in 2 decimal places - Mkyong.com
October 29, 2021 - In Java, we can use DecimalFormat("0.00"), String.format("%.2f") or BigDecimal to display double in 2 decimal places.
🌐
Java2Blog
java2blog.com › home › number › format double to 2 decimal places in java
Format Double to 2 Decimal Places in Java [ 7 Ways ] - Java2Blog
November 8, 2023 - DecimalFormat can be used by providing formatting Pattern to format double to 2 decimal places. We can use RoundingMode to specify rounding behavior. Here is an example: ... Double upto 2 decimal places: 2.46 Double upto 2 decimal places – ...
🌐
Coderanch
coderanch.com › t › 689796 › java › format-double-decimal
format a double decimal (Beginning Java forum at Coderanch)
Now, back to my original question, on the decimal formatting to 3 digits, line 17 is supposed to return the bmi with 3 decimal places, however I only receive the error "The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, double)" Any ideas what I am doing wrong? ... If the 4 digit number is created in one statement, there is not need for a loop. ... Now you don't need the loop, but you are ruling out id's that start with a zero. A java 8 stream version could be:
🌐
Java67
java67.com › 2014 › 06 › how-to-format-float-or-double-number-java-example.html
5 Examples of Formatting Float or Double Numbers to String in Java | Java67
For example you can use method printf() to format a float or double number to a output stream. However, it does not return a String. In JDK 1.5, a new static method format() was added to the String class, which is similar to printf(), but returns ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-convert-double-to-string
Java Convert double to String | DigitalOcean
August 3, 2022 - However java supports autoboxing, so they both can be used interchangeably in most of the cases. This is the easiest way to convert double to string in java.
🌐
Reddit
reddit.com › r/javahelp › print exact value of double
r/javahelp on Reddit: Print exact value of double
January 7, 2024 -

When I do

System.out.printf("%.50f", 0.3);

it outputs 0.30000000000000000000000000000000000000000000000000 but this can't be right because double can't store the number 0.3 exactly.

When I do the equivalent in C++

std::cout << std::fixed << std::setprecision(50) << 0.3;

it outputs 0.29999999999999998889776975374843459576368331909180 which makes more sense to me.

My question is whether it's possible to do the same in Java?

Top answer
1 of 4
2
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; }
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Coderanch
coderanch.com › t › 493635 › java › set-decimals-digits-Doubles
How to set decimals to only 2 digits in Doubles? (Beginning Java forum at Coderanch)
If you don't want to print it, but just return the result formatted in a string, use String.format("%.2f", number); instead (that returns a String). Another, slightly more cumbersome way, is to use class java.text.NumberFormat.