From java.util.Formatter documentaion: you can use the g modifier, precision field to limit the number to a specific number of characters and the width field to fill it with the column width.
String.format("%1$8.5g", 1000.4213);
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
Although precision does not include the point and length of the exponent, only the numbers in the mantissa are counted.
Keeping extra space for the point and cutting out additional numbers from the fractional part, if the line is much wider, which can also be solved.
String num = String.format("%1$ .5g", input); if (num.length > 6) num = num.substring(0, 2) + num.substring(7);
The scientific format of the number always follows a strict set of rules, so we do not need to look for a point inside the line to cut a fraction from the line if the character is always on (or, as in the case above, replaced by a space character for positive numbers).
source share