I want to round my number if it exceeds 8 character long.
For example,
// Big number rounding using scientific notation
double myDouble1 = 123456789;// desired output: 1.23e+08
Another situation
// Rounding
double myDouble2 = 12345.5678901234; // Desired output: 12345.57
I've tried using String.format()
with %.2g
and %.7
, but I couldn't achieve the desired output.
Here's the code that I've tried to come up with.
public String parseResult(String val){
String formatted = val;
try{
if(formatted.length() > 8){
double temp = Double.parseDouble(val);
if(temp % 1 == 0){
formatted = String.format("%.2g", temp);
}else{
formatted = String.format("%.7g", temp);
}
}
}
catch(NumberFormatException e)
{
}
return formatted;
}