Scientific notation format
In this chapter you will learn:
- What specifier is for scientific notation format
- How to choose between decimal format and scientific notation
%e is for scientific notation format
To format a floating-point value in scientific notation, use %e.
Numbers represented in scientific notation take this general form:
x.dddddde+/-yy
The following code format value to 2 decimal places in a 16 character field.
import java.util.Formatter;
/* ja va2 s . c o m*/
public class MainClass {
public static void main(String args[]) {
Formatter fmt = new Formatter();
// Format to 2 decimal places in a 16 character field.
fmt = new Formatter();
fmt.format("%16.2e", 123.1234567);
System.out.println(fmt);
}
}
The output:
Choose between decimal format and scientific notation
The %g format specifier causes Formatter to use either %f or %e, whichever is shorter.
The following program demonstrates the effect of the %g format specifier:
// Demonstrate the %g format specifier.
import java.util.Formatter;
/*from ja v a2 s .co m*/
public class Main {
public static void main(String args[]) {
Formatter fmt = new Formatter();
for (double i = 1000; i < 1.0e+10; i *= 100) {
fmt.format("%g ", i);
System.out.println(fmt);
}
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- What specifiers to use to format octal and hexadecimal value
- How to format floating-point values in hexadecimal format
Home » Java Tutorial » String