I need precision math of maximum 4 decimals that need to be converted to string in order to proceed further with the result in my code and in case the result has more that 4decimals I would like to get the result approximation. Ex: for 3.3333333333 -> 3.3334
My current code is quite messy, but works. Is there is an easier way around this?
...............
Double rez = (Double) engine.eval(foo); // some rezult as double from the rest of code
//convert foo to my string
String implem = String.valueOf(rez);
rezultat = implem; // rezultat -> is the string returned of the function
if(implem.contains(".")){
String []splitter =implem.split("\\.");
// System.out.println(splitter[0]+" length:"+splitter[0].length());
// System.out.println(splitter[1]+" length:"+splitter[1].length());
if(splitter[1].length()>4){
String ceva=splitter[1].substring(0,4);
byte subb[]=ceva.getBytes();
char c = (char)subb[3];
// System.out.println((char)subb[0]+">"+(char)subb[1]+">"+(char)subb[2]+">"+(char)subb[3]+" :those are the splits");
if(subb[0]==subb[1] && subb[1]==subb[2] && subb[2]==subb[3] && (char) subb[0]=='9'){
//in case of 9999
long numer = Long.parseLong(splitter[0]);
numer++;
splitter[0]=String.valueOf(numer);
rezultat = splitter[0];
return rezultat; // program returns next Long value (without decimals)
}
// System.out.println(subb[0]+"+"+subb[1]+"+"+subb[2]+"+"+subb[3]+" value of subb[3]:"+c);
if(c!='0'){
int kappa = Integer.parseInt(ceva);
kappa++;
String partCeva = String.valueOf(kappa); //in case of integer<1000 -- add 0's
while(partCeva.length()<4){
partCeva= "0"+partCeva;
}
ceva=partCeva;
}
Double fin = Double.parseDouble(splitter[0]+"."+ceva); //do this to remove unwanted 0
rezultat = fin.toString();
}
else{
rezultat = splitter[0]+"."+splitter[1];
}
...........
return rezultat ; }