Domanda

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?

È stato utile?

Soluzione 3

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();    
}

Altri suggerimenti

Im pretty sure you cant, as what your asking is for DecimalFormat to show a different number than what you are representing

Why not apply DecimalFormat to return the String 12.4 then substring the portion in front of the e if you need String format? Or just multiply out based on the exponent?

To get 2 decimal places before the digits and one after you can do the following.

String s = String.format("%4.1f", d / 
                              Math.pow(10, (int) (Math.log10(Math.abs(d)) - 1)));

Of course believing that the number after 999 => 99.9 is 1000 => 10.0 is just madness.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top