The `DecimalFormat`

class
is useful for medium-sized numbers, but it doesn’t work very
well for exceptionally large numbers like Avogadro’s number
(6,022,094,300,000,000,000,000,000) or exceptionally small numbers
like Planck’s constant (0.00000000000000000000000000625
erg-seconds). These are traditionally written in scientific notation
as a decimal number times 10 to a certain power, positive or
negative; for example, 6.0220943 ×
10^{23} and 6.25 ×
10^{-27} erg-seconds. In most programming
languages, including Java, an E followed by either a + or a - is used
to represent “× 10 to the power”; for example,
6.0220943E+23 or 6.25E-27 erg-seconds.

The `java.text`

package does not provide support for
formatting numbers in scientific notation,^{[32]} so as the final example of this chapter, I’ll
develop a new subclass of `NumberFormat`

that does
use scientific notation. Technically, scientific notation requires
exactly one nonzero digit before the decimal point, but I’ll be
a little more general than that, providing for numbers like 13.2E-8
as well.

The `NumberFormat`

class is abstract. It declares
three abstract methods any subclass must implement:

public abstract StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) public abstract StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) public abstract Number parse(String text, ParsePosition parsePosition)

The two format methods must format a `long`

and a
`double`

respectively, update ...

Start Free Trial

No credit card required