I want to display only the mantissa of a number independently of what the exponent is.
12.4e-6 after formatting => 12.4
12.4e-12 after formatting => 12.4
To do the calculation manually is trivial. But the problem is that I need to use the class DeciamalFormat because I have to give it as argument to another class. I tried this:
DecimalFormat mFormat = (DecimalFormat) NumberFormat.getInstance();
mFormat.applyPattern("#.#E0");
if I remove the E symbol, the mantissa will not be calculated. is there any way using this DecimalFormat
to show only mantissa
?
I have found following solution: I override the methods of the NumberFormat class so that I can manipulate how the Double values are transformed into Strings:
public class MantissaFormat extends NumberFormat {
@Override
/** Formats the value to a mantissa between [0,100] with two significant decimal places. */
public StringBuffer format(double value, StringBuffer buffer, FieldPosition field) {
String output;
String sign="";
if(!isFixed)
{
if(value<0)
{
sign = "-";
value = -value;
}
if(value!=0) {
while(value<1) {
value *= 100;
}
while(value>100){
value/=100;
}
}
}
// value has the mantissa only.
output = sign + String.format( "%.2f", value );
buffer.append(output);
return buffer;
}
@Override
public Number parse(String string, ParsePosition position) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}