java - Display 2 floats rounded up to 2 decimal places without losing which one is bigger -


i 2 numbers num1 , num2 network service can represented double , have unknown number of decimal places (i mean 3, 4 or 5 etc).
these numbers represent percentage 0.34567 34.567%
need display them 2 decimal places (or no decimal places instead of e.g. 34.00%) if num1 greater num2.

i tried 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 approach , result? may thinking wrong?

for ceation of 2 decimal places do:

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

if divide 100 instead of 10_000 directly percent.

and removing zeros convert number string with

string.valueof(num) 

and search regex pattern

"\\.0" 

and act accordingly removing if found.

complet solution (a bit diffrent, because had trouble regex):

//rounding on 2 decimalplaces , writing 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 percent char @ end system.out.println(numxstr) //outputting 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -