简体   繁体   中英

Scientific notation with fixed number of fractional digits in Java

I'm trying to use decimalFormat to display decimal numbers in scientific notation after a fixed number of fractional digits like this:

DecimalFormat df = new DecimalFormat("0.####E0");
System.out.println(df.format(0.2222));

In this example, I used the pattern "0.####E0" to set the number of fractional digits to be 4 and the program outputs 2.222E-1.

Now this is what I got for different input values:

Five fractional digits: 0.22222 = 2.2222E-1
Six fractional digits: 0.22222 = 2.22222E-1
Seven fractional digits: 0.22222 = 2.22222E-1

And so on...

What I want to do is instead of 2.222222E-1, the program should display 2.2222E-3. So any help please and thanks

What I want to do is instead of 2.222222E-1, the program should display 2.2222E-3

No. Your logic is incorrect E-1 means 10 -1 and for your input 0.2222 you have 2.222E-1 means 2.222 * 10 -1 now you can not have value 2.2222 * 10 -3 Why? because than the value would be 0.0022222 and not 0.2222

Sorry guys, I meant 222.2222E-3

No. For value 0.2222 you can not have 222.2222E-3 which means 222.2222 *10 -3 and value will be 0.2222222 which is still different. Moreover have a look at DecimalFormat documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM