Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: double: how to ALWAYS show two decimal digits

I use double values in my project and I would like to always show the first two decimal digits, even if them are zeros. I use this function for rounding and if the value I print is 3.47233322 it (correctly) prints 3.47. But when I print, for example, the value 2 it prints 2.0.

public static double round(double d) {     BigDecimal bd = new BigDecimal(d);     bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);     return bd.doubleValue(); } 

I want to print 2.00!

Is there a way to do this without using Strings?

EDIT: from your answers (which I thank you for) I understand that I wasn't clear in telling what I am searching (and I'm sorry for this): I know how to print two digits after the number using the solutions you proposed... what i want is to store in the double value directly the two digits! So that when I do something like this System.out.println("" + d) (where d is my double with value 2) it prints 2.00.

I'm starting to think that there is no way to do this... right? Thank you again anyway for your answers, please let me know if you know a solution!

like image 776
aveschini Avatar asked Jun 12 '13 07:06

aveschini


People also ask

How do you double only show two decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

How do you show only 2 decimal places in Java?

printf("%. 2f", value); The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (.

Can double hold decimals in Java?

The number of decimal places in a double is 16.


1 Answers

You can use something like this:

 double d = 1.234567;  DecimalFormat df = new DecimalFormat("#.00");  System.out.print(df.format(d)); 

Edited to actually answer the question because I needed the real answer and this came up on google and someone marked it as the answer despite the fact that this wasn't going to work when the decimals were 0.

like image 180
Peter Jaloveczki Avatar answered Sep 22 '22 18:09

Peter Jaloveczki