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 precisionto 6 in this case)
0.0000073943162953
-> 7.39432E-6
(switch to scientific notation if the magnitude is small enoughless than 1E-5
in this case)
7394316295300000
-> 7.39432E+6
(switch to scientific notation if the magnitude is large enoughfor 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:
.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."%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
.
Have you looked at DecimalFormat yet?
(what might also be of interest: BigDecimal#toString())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With