Double decimal formatting in Java
One of the way would be using NumberFormat.
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(4.0));
Output:
4.00
How to print a float with 2 decimal places in Java?
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
Round a double to 2 decimal places
Here's an utility that rounds (instead of truncating) a double to specified number of decimal places.
For example:
round(200.3456, 2); // returns 200.35
Original version; watch out with this
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)
) or large integer part (e.g. round(90080070060.1d, 9)
). Thanks to Sloin for pointing this out.
I've been using the above to round "not-too-big" doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it's best to avoid it, since more reliable ways are readily available, with cleaner code too.
So, use this instead
(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
Note that HALF_UP
is the rounding mode "commonly taught at school". Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.
Of course, if you prefer, you can inline the above into a one-liner:new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()
And in every case
Always remember that floating point representations using float
and double
are inexact.
For example, consider these expressions:
999199.1231231235 == 999199.1231231236 // true
1.03 - 0.41 // 0.6200000000000001
For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:
System.out.println(new BigDecimal(1.03).subtract(new BigDecimal(0.41)));
System.out.println(new BigDecimal("1.03").subtract(new BigDecimal("0.41")));
Some excellent further reading on the topic:
- Item 48: "Avoid
float
anddouble
if exact answers are required" in Effective Java (2nd ed) by Joshua Bloch - What Every Programmer Should Know About Floating-Point Arithmetic
If you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.
Specifically, note that round(200, 0)
returns 200.0
. If you want to output "200.00", you should first round and then format the result for output (which is perfectly explained in Jesper's answer).
Best way to Format a Double value to 2 Decimal places
No, there is no better way.
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00"
, meaning exactly two decimal places.
If you use "#.##"
(#
means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d);
prints just "3"
, not "3.00"
.
Double with specific format and two decimals
You don't want to combine NumberFormat
and String.format()
.
You can further configure your NumberFormat
object to tell it to use two decimal places:
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH);
numberFormat.setMinimumFractionDigits(2);
assertThat(numberFormat.format(1007.2), is("1 007,20"));
(and possibly setMaximumFractionDigits()
etc., depending on your needs -- see the Javadoc)
Take care - NumberFormat.format()
is not thread-safe.
Alternatively you can use String.format(locale, format, args)
:
assertThat(String.format(Locale.CANADA_FRENCH, "%,.2f", 1007.2), is("1 007,20"));
The ,
flag in the format tells the formatter to use a thousands-separator, and the locale tells it that the separator is a space.
How to remove decimal values from a value of type 'double' in Java
You can convert the double
value into a int
value.int x = (int) y
where y is your double variable. Then, printing x
does not give decimal places (15000
instead of 15000.0
).
Format, 2 decimal places for double and 0 for integer in java
The only solution i reached is to use if statement like was mentioned here: https://stackoverflow.com/a/39268176/6619441
public static boolean isInteger(BigDecimal bigDecimal) {
int intVal = bigDecimal.intValue();
return bigDecimal.compareTo(new BigDecimal(intVal)) == 0;
}
public static String myFormat(BigDecimal bigDecimal) {
String formatPattern = isInteger(bigDecimal) ? "#,##0" : "#,##0.00";
return new DecimalFormat(formatPattern).format(bigDecimal);
}
Testing
myFormat(new BigDecimal("100")); // 100
myFormat(new BigDecimal("100.1")); // 100.10
If someone knows more elegant way, please share it!
DecimalFormat not formatting a double having value equal to 0
Yes. You can use the 0
formatting element instead of #
which involves 0-padding, e.g.
Double c = 0.0d;
DecimalFormat df2 = new DecimalFormat("00.00");
System.out.println("c = "+df2.format(c));
As mentioned in the docs:
Symbol Location Localized? Meaning
0 Number Yes Digit
# Number Yes Digit, zero shows as absent
Java formatting decimals to 2 digits precision
You should use:
DecimalFormat df = new DecimalFormat("#.00");
DecimalFormat df = new DecimalFormat("#.##");
means, that those decimal places are optional. You can see the difference when applying on 1.2
or 1.0
.
--Documentation
Double decimal formatting issue
If you want control over the rounding used in converting a double
to a String
you need to use DecimalFormat
.
You either want FLOOR
,which rounds towards negative infinity, or DOWN
, which rounds towards zero, depending on the desired behavior with negative numbers (for positive numbers they produce the same results):
DecimalFormat df = new DecimalFormat(".##");
df.setRoundingMode(RoundingMode.FLOOR);
System.out.println("FLOOR");
System.out.println(df.format(8.775));
System.out.println(df.format(-8.775));
System.out.println("DOWN");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(8.775));
System.out.println(df.format(-8.775));
Output:
FLOOR
8.77
-8.78
DOWN
8.77
-8.77
Related Topics
Maximum Java Heap Size of a 32-Bit Jvm on a 64-Bit Os
Platform.Runlater and Task in Javafx
Read a PDF File from Assets Folder
Android: How to Get the Current Day of the Week (Monday, etc...) in the User's Language
Listview Onitemclicklistener Not Responding
Connect to SQL Server from Linux via Jdbc Using Integratedsecurity (Windows Authentication)
Java App Behind Proxy to Use Http_Proxy Variable in Linux
Is a Java Filelock a Posix Advisory (Fcntl) Lock
Match Multiline Text Using Regular Expression
Can You Use @Autowired With Static Fields
Manifest Merger Failed:Attribute Application@Appcomponentfactory Cant Solve This
Read_External_Storage Permission for Android
Find Directory for "Application Data" on Linux and MACintosh
Force Jvm to Do All Io Without Page Cache (E.G. O_Direct)
How Does Linux Recognize a File as a Certain File Type, and How to Programmatically Change It