kostmo
kostmo

Reputation: 6340

compact Number formatting behavior in Java (automatically switch between decimal and scientific notation)

I am looking for a way to format a floating point number dynamically in either standard decimal format or scientific notation, depending on the value of the number.

Basically, it should optimize for compactness and readability.

2.80000 -> 2.8

765.000000 -> 765

0.0073943162953 -> 0.00739432 (limit digits of precision—to 6 in this case)

0.0000073943162953 -> 7.39432E-6 (switch to scientific notation if the magnitude is small enough—less than 1E-5 in this case)

7394316295300000 -> 7.39432E+6 (switch to scientific notation if the magnitude is large enough—for example, when greater than 1E+10)

0.0000073900000000 -> 7.39E-6 (strip trailing zeros from significand in scientific notation)

0.000007299998344 -> 7.3E-6 (rounding from the 6-digit precision limit causes this number to have trailing zeros which are stripped)


Here's what I've found so far:

I'm wondering if there's already some library function out there that meets these criteria. I guess the only stumbling block for writing this myself is having to strip the trailing zeros from the significand in scientific notation produced by %G.

Upvotes: 6

Views: 1969

Answers (1)

Tedil
Tedil

Reputation: 1933

Have you looked at DecimalFormat yet?

(what might also be of interest: BigDecimal#toString())

Upvotes: 1

Related Questions