Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I convert a float to a String and always get a resulting string of a specified length?

For example, if I have

float f = 0.023f;

and I want a 6 character string, I'd like to get 0.0230. But if I want to convert it to a 4 character string the result should be 0.02. Also, the value -13.459 limited to 5 characters should return -13.4, and to 10 characters -13.459000.

Here's what I'm using right now, but there's gotta be much prettier ways of doing 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);
like image 386
Magnus Avatar asked Oct 29 '22 09:10

Magnus


1 Answers

From java.util.Formatter documentaion: you can use g modifier, precision field to limit number to specific number of characters and width field for padding it to column width.

String.format("%1$8.5g", 1000.4213);

https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html


Though precision doesn't include dot and exponent length – only digits in mantissa counted.

By keeping extra place for dot and cutting extra digits from fractional part if string is significantly wider that could be solved too.

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'

Scientific format of number always follows strict set of rules, so we don't have to search for dot inside string to cut fraction out of string if sign is always included (or, like in case above – replaced by space character for positive numbers).

like image 65
weaknespase Avatar answered Nov 15 '22 04:11

weaknespase