Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert scientific notation to decimal notation

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?

like image 516
Ankur Avatar asked Feb 25 '26 21:02

Ankur


2 Answers

Memorize the String.format syntax so you can convert your doubles and BigDecimals to strings of whatever precision without e notation:

This java code:

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

Prints:

8.88E-8
0.0000001
0.000000089
0.0000000888000000000
like image 157
Eric Leschinski Avatar answered Feb 28 '26 12:02

Eric Leschinski


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".

like image 30
Jacob Mattison Avatar answered Feb 28 '26 13:02

Jacob Mattison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!