rounding a double in a number of significant numbers
After calulating some number i need to round the result into a "variable" (only 2 or 3) number of significant figures.
0.00245 2 --> 0.0025 3 --> 0.00245
5141.0 2 --> 5100.0 3 --> 5140.0
1.0202 2 --> 1.0 3 --> 1.02
I couldn't found a standard solution in the JAVA API. I tried the Decimal formatter but this only rounds to a number of figures behind the . (I don't know the exact english term but 0.000022115 is shown as 0.00 instead of 0.000022).
There is a mathematical formula for rounding. I implemented as following in my code:
static public Double roundDouble(Double l_value, Integer a_NumberOfSignificantFigures)
Double l_roundedvalue = null;
if (l_value != null && a_NumberOfSignificantFigures > 0 && l_value > 0.0)
// this truncates all irrelevant numbers
double l_exp = Math.floor((Math.log10(l_value)- a_NumberOfSignificantFigures + 1));
double l_power = Math.pow(10, l_exp);
l_roundedvalue = Math.floor((l_value/l_power) + 0.5) * l_power;
// if rounding is not possible return original result
l_roundedvalue = l_value;
To display the rounded values I use the toString() method.
The result is that in most cases the result is as expected but for some there result is shown as:
250.000000000002 or 0.00000098000004.
I am aware of the fact that this happens with floating point precision.
However I'm looking for a solution to print the two examples above as 250.0 and 00000098 (in case of 2 significant figures). I don't want to use the scientific notation.
The only solution I can think of is to write my own string formatter to display the doubles correct. However I cannot imagine there isn't a standard java solution to this problem.
Any help is appreciated.