Convert float to string and always get a specific string length?

How to convert float to String and always get the resulting string of the specified length?

For example, if I have

 float f = 0.023f; 

and I need a string of 6 characters, I would like to get 0.0230 . But if I want to convert it to a string with 4 characters, the result should be 0.02 . In addition, a value of -13.459 limited to 5 characters should return -13.4 and up to 10 characters -13.459000 .

Here is what I'm using right now, but there should be a lot more beautiful ways to do this ...

 s = String.valueOf(f); s = s.substring(0, Math.min(strLength, s.length())); if( s.length() < strLength ) s = String.format("%1$-" + (strLength-s.length()) + "s", s); 
+5
source share
1 answer

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); //100300 => ' 1e+05'; 512.334 => ' 512.33' 

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).

+3
source

Source: https://habr.com/ru/post/1266641/


All Articles