简体   繁体   中英

DecimalFormat not giving proper output in Java

I'm learning Java and have gotten to a section teaching about different Java Utilities and number formatting. However, my formatting is not working the same as they say it should in the book. My code looks like this:

import java.text.NumberFormat;
import java.text.DecimalFormat;

public class Lessons {

public static void main(String[] args) {

    double d = 7.1348759272948202842847;

    System.out.printf("%15e %n", d);

    NumberFormat cashFormat = NumberFormat.getCurrencyInstance();

    System.out.println(cashFormat.format(d));

    double e = 14.9;
    double f = 16.09805938020001;
    double g = 12346;

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

    System.out.println(Dec_Format.format(e));
    System.out.println(Dec_Format.format(f));
    System.out.println(Dec_Format.format(g));
}

In the book example, it says that 12345 formatted with "##0.##E0" is "12.3E3". The output I'm receiving is "12.345E3".

The output that I'm receiving makes sense, but since it doesn't match the book, I'm not sure if it's an error in the book or if I'm doing something wrong.

Is this the normal output?

The format that you are using to print 12.3E3 is not correct so instead to :

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

you should to use :

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

This will show you :

   7,134876e+00 
7,13 €
14,9E0
16,1E0
12,3E3//<-----------------

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