1.5 is the number of significant digits, as well as 1.50 (and even 1.5000000000000 ).
You need to separate the meaning of the number from its representation.
If you want it to be output with two decimal places, just use String.format , for example:
public class Test { public static void main(String[] args) { double d = 1.50000; System.out.println(d); System.out.println(String.format("%.2f", d)); } }
which outputs:
1.5 1.50
If you still need a function that does all this for you and gives you a specific format, you need to return a string with something like:
public static String roundOff(double num, double acc, String fmt) { num *= acc; num = Math.ceil(num); num /= acc; return String.format(fmt, num); }
and name it with:
resultString = roundOff(value, 20, "%.2f"); // or 100, see below.
This will allow you to adjust the precision and output format in any way, although you can still hard code the values ββif you want simplicity:
public static String roundOff(double num) { double acc = 20; String fmt = "%.2f"; num *= acc; num = Math.ceil(num); num /= acc; return String.format(fmt, num); }
One final note: your question says that you want to round to βtwo decimal placesβ, but this is not really a gel with your use of 20 as precision, since it rounds it to the next multiple of 1/20. If you really want to round to two decimal places, the value you should use for accuracy is 100 .