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

1

6

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.

  • For moderate magnitudes, the number should be formatted as a decimal with trailing zeros suppressed. If the floating point number is equal to an integral value, the decimal point should also be suppressed.
  • For extreme magnitudes (very small or very large), the number should be expressed in scientific notation. Alternately stated, if the number of characters in the expression as standard decimal notation exceeds a certain threshold, switch to scientific notation.
  • I should have control over the maximum number of digits of precision, but I don't want trailing zeros appended to express the minimum precision; all trailing zeros should be suppressed.

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:

  • The .toString() method of the Number class does most of what I want, except it doesn't upconvert to integer representation when possible, and it will not express large integral magnitudes in scientific notation. Also, I'm not sure how to adjust the precision.
  • The "%G" format string to the String.format(...) function allows me to express numbers in scientific notation with adjustable precision, but does not strip trailing zeros.

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.

Zosima answered 13/11, 2011 at 9:43 Comment(0)
W
1

Have you looked at DecimalFormat yet?

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

Workhorse answered 13/11, 2011 at 10:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.