Convert scientific notation to decimal notation

There is a similar SO question that suggests using NumberFormat, which I did.

I am using the parse () method for 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 is

1.93

I really did not expect this to work because 1.930000000000E + 02 is a rather unusual looking number, do I need to parse strings first to remove zeros? Or is there a quick and elegant way?

+3
source share
3 answers

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

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

javadocs DecimalFormat - "Scientific Notation".

+2

String.format, BigDecimals :

Java:

double dennis = 0.00000008880000d;
System.out.println(dennis);
System.out.println(String.format("%.7f", dennis));
System.out.println(String.format("%.9f", new BigDecimal(dennis)));
System.out.println(String.format("%.19f", new BigDecimal(dennis)));

8.88E-8
0.0000001
0.000000089
0.0000000888000000000
+3

, String, printf magic.

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

2 . 193.00.

"%.2e" , "1.93e+02"

( , , .)

+1

Source: https://habr.com/ru/post/1737018/


All Articles