I have a very simple code and I am not used to deal with libraries, yet. I want a way to round the number like what we do in "C" (%.2).
Asked
Active
Viewed 1,085 times
-1
-
Do you mean there is no simple way? – Ibrahim Alawwad Oct 02 '15 at 00:51
-
Do the standard libraries, the JDK, count as _libraries_? – Sotirios Delimanolis Oct 02 '15 at 00:52
2 Answers
2
It depends on exactly what you want to do. If you are seeking the equivalent of C's
printf("%.2f", doubleValue);
you can use:
System.out.println( String.format("%.2f", doubleValue) );
This uses standard Java code that would be available in all JVMs, ie. no external libraries are required.

dave
- 11,641
- 5
- 47
- 65
-
-
You could also just write `System.out.printf("%.2f%n", doubleValue)`. – Louis Wasserman Oct 02 '15 at 00:59
-
@IbrahimAlawwad Happy to help. You can of course accept my answer (hint, hint) :) – dave Oct 02 '15 at 01:14
1
If I understand the question correctly,
double x = 1.2764;
double x_to_2_decimals = (int)(x * 100 + 0.5) / 100.0;

Amadan
- 191,408
- 23
- 240
- 301