我需要精确数学最多4个小数,需要转换为字符串,以便在我的代码中继续进行结果,如果结果有更多4个十进制,我想得到结果近似值。 例如:3.3333333333 - > 3.3334
我目前的代码非常混乱,但有效。有更简单的方法吗?
...............
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 ; }
答案 0 :(得分:1)
你可以做到
double x = (Double) engine.eval(foo);
使用double或float舍入到String。
return String.format("%4f", x);
使用BigDecimal
舍入到Stringreturn BigDecimal.valueOf(x).setScale(4, RoundingMode.HALF_UP).toString();
值3.3333333333通常四舍五入为3.3333但是有一种模式可以向上舍入到下一个值。