views:

330

answers:

2

There is a similar question on SO which suggests using NumberFormat which is what I have done.

I am using the parse() method of NumberFormat.

public static void main(String[] args) throws ParseException{

    DecToTime dtt = new DecToTime();
    dtt.decToTime("1.930000000000E+02");

}

public void decToTime(String angle) throws ParseException{

    DecimalFormat dform = new DecimalFormat();
    //ParsePosition pp = new ParsePosition(13);
    Number angleAsNumber = dform.parse(angle);

    System.out.println(angleAsNumber);
}

The result I get is

1.93

I didn't really expect this to work because 1.930000000000E+02 is a pretty unusual looking number, do I have to do some string parsing first to remove the zeros? Or is there a quick and elegant way?

+1  A: 

When you use DecimalFormat with an expression in scientific notation, you need to specify a pattern. Try something like

DecimalFormat dform = new DecimalFormat("0.###E0");

See the javadocs for DecimalFormat -- there's a section marked "Scientific Notation".

JacobM
+1  A: 

If you take your angle as a double, rather than a String, you could use printf magic.

System.out.printf("%.2f", 1.930000000000E+02);

displays the float to 2 decimal places. 193.00 .

If you instead used "%.2e" as the format specifier, you would get "1.93e+02"

(not sure exactly what output you want, but it might be helpful.)

rascher