I get two numbers num1 and num2 from a network service that can be represented by a double and have an unknown number of decimal places (I mean could be 3, 4 or 5 etc).

These numbers represent a percentage so could be something like 0.34567 which is 34.567%

I need to display them with 2 decimal places (or no decimal places instead of e.g. 34.00%) if num1 is greater than num2.

I tried the following:

String num1 = "0.3547"; String num2 = "0.354"; int fixed = 2; int diff = Math.abs(num1.length() - num2.length()); double tmp = 0.0d; double d1 = Double.valueOf(num1); double d2 = Double.valueOf(num2); tmp = (d1 > d2)? d1 : d2; while(diff > 0) { StringBuilder sb = new StringBuilder("%."); sb.append(String.valueOf(fixed + diff)).append("f"); String formatter = sb.toString(); System.out.println(formatter); String round = String.format(formatter, tmp); tmp = Double.parseDouble(round); --diff; } String final1 = String.format("%.2f", tmp); String final2 = String.format("%.2f", (d1 < d2)? d1 : d2); System.out.println(final1 + " vs " + final2);

The output is:

0.36 vs 0.35

How sane is this approach and the result? May be I am thinking this wrong?

For ceation of two decimal places just do:

num = (Maht.round(num * 10_000)) num /= 10_000

If you just divide by 100 instead of 10_000 you get directly percent.

and for removing zeros just convert the number to a String with

String.valueOf(num)

and search for the regex pattern

"//.0"

and act accordingly by removing it if it is found.

Complet solution (a bit diffrent, because I had some trouble with regex):

//Rounding on to two decimalplaces and writing to a String numX = (Math.round(numX * 10_000)); String numXStr = String.valueOf(numX /= 100); //Removing of ".0" endings if (numXStr .endsWith(".0")) { numXStr = numXStr .substring(0, numXStr .length() - 2); } numXStr += "%"; //Adding the percent char at the end System.out.println(numXStr) //outputting