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

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

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

Related

Add zeros to the left of Number

I know that I can add left zeros to String but what about Long?
I need to put left zeros until the Long size is 10 digits. For example, if it's 8 digits (12345678), it should add 2 left zeros (0012345678)
I want to add this in the getValue() method.
public Long getValue() {
// Should always be 10 digits, If it's 8, add zeros
return value;
}
I'm using spring. This issue is that the database that cuts the left zeros. Maybe is there a annotation to avoid extra code?
This is not possible. A Long does not contain data about the String representation of its value. In fact, the Long is actually stored in binary, not decimal, and the long object is unaware of this.
If you want to convert it to a String with leading zeroes, String.format("%017d" , number); will pad it to make sure it has 10 digits.
In java, a long (wrapped in a Long) will always be stored on 8 bytes,
There is no way to "add" extra zeros as they're already existing.
Either your database must change its type to String and add padding zeros when you store your Long object either change your inner code to String and add padding zeros when you pull the data from your Long in db.
You cannot because a long does not have a leading zero.
A string of characters like 0012345678 is not an integer, 12345678 is.
but there are two way in java to add leading zeroes
WAY 1: format() method
int number = 9;
String str = String.format("%04d", 9); // 0009
System.out.printf("original number %d, numeric string with padding : %s", 9, str);
WAY 2 : DecimalFormat
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // 0009
String a = df.format(99); // 0099
String b = df.format(999); // 0999
but in both case you get string instead of Long
for more reading
Try this one,
int number = 12345678;
String str = String.format("%10d", number);
System.out.println("original number %d, numeric string with padding : %s", number, str);

Formatting Java output [duplicate]

I need to create a summary table at the end of a log with some values that
are obtained inside a class. The table needs to be printed in fixed-width
format. I have the code to do this already, but I need to limit Strings,
doubles and ints to a fixed-width size that is hard-coded in the code.
So, suppose I want to print a fixed-width table with
int,string,double,string
int,string,double,string
int,string,double,string
int,string,double,string
and the fixed widths are: 4, 5, 6, 6.
If a value exceeds this width, the last characters need to be cut off. So
for example:
124891, difference, 22.348, montreal
the strings that need to be printed ought to be:
1248 diffe 22.348 montre
I am thinking I need to do something in the constructor that forces a
string not to exceed a certain number of characters. I will probably
cast the doubles and ints to a string, so I can enforce the maximum width
requirements.
I don't know which method does this or if a string can be instantiated to
behave taht way. Using the formatter only helps with the
fixed-with formatting for printing the string, but it does not actually
chop characters that exceed the maximum length.
You can also use String.format("%3.3s", "abcdefgh"). The first digit is the minimum length (the string will be left padded if it's shorter), the second digit is the maxiumum length and the string will be truncated if it's longer. So
System.out.printf("'%3.3s' '%3.3s'", "abcdefgh", "a");
will produce
'abc' ' a'
(you can remove quotes, obviously).
Use this to cut off the non needed characters:
String.substring(0, maxLength);
Example:
String aString ="123456789";
String cutString = aString.substring(0, 4);
// Output is: "1234"
To ensure you are not getting an IndexOutOfBoundsException when the input string is less than the expected length do the following instead:
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);
If you want your integers and doubles to have a certain length then I suggest you use NumberFormat to format your numbers instead of cutting off their string representation.
For readability, I prefer this:
if (inputString.length() > maxLength) {
inputString = inputString.substring(0, maxLength);
}
over the accepted answer.
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);
You can use the Apache Commons StringUtils.substring(String str, int start, int end) static method, which is also null safe.
See: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#substring%28java.lang.String,%20int,%20int%29
and http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/src-html/org/apache/commons/lang/StringUtils.html#line.1961
You can achieve this easily using
shortString = longString.substring(0, Math.min(s.length(), MAX_LENGTH));
If you just want a maximum length, use StringUtils.left! No if or ternary ?: needed.
int maxLength = 5;
StringUtils.left(string, maxLength);
Output:
null -> null
"" -> ""
"a" -> "a"
"abcd1234" -> "abcd1"
Left Documentation
The solution may be java.lang.String.format("%" + maxlength + "s", string).trim(), like this:
int maxlength = 20;
String longString = "Any string you want which length is greather than 'maxlength'";
String shortString = "Anything short";
String resultForLong = java.lang.String.format("%" + maxlength + "s", longString).trim();
String resultForShort = java.lang.String.format("%" + maxlength + "s", shortString).trim();
System.out.println(resultForLong);
System.out.println(resultForShort);
ouput:
Any string you want w
Anything short
Ideally you should try not to modify the internal data representation for the purpose of creating the table. Whats the problem with String.format()? It will return you new string with required width.

Java Floats formatting

There is e.x 2.52549856E8 float number.
What I want is simply make it 25.2549856E8, that's it, everything else can stay.
I sought for solution and all I found was with bunch of string examples.
I get pure float number. Should I convert it to String first? Is there a simpler way to do this?
if you want to just move the dot one digit to the right, you can use following snippet, which uses String#substring() to cut the String into the right parts and then concatenates them again:
String number = String.valueOf(2.52549856E8f);
int index = number.indexOf('.');
String formatted =
number.substring(0, index) +
number.substring(index + 1, index + 2) +
'.' +
number.substring(index + 2);
number.substring(0, index) cuts the first digit out
number.substring(index + 1, index + 2) cuts the second digit out
'.' inserts the new dot
number.substring(index + 2) appends the rest of the number
The same can be done with regex:
String number = String.valueOf(2.52549856E8f);
String formatted = number.replaceAll("^(\\d)\\.(\\d)(\\d+E\\d+)$", "$1$2.$3");

One "0" is missing in my binary - how can I fix it? [duplicate]

This question already has answers here:
How to convert a long to a fixed-length 16-bit binary string?
(8 answers)
Closed 5 years ago.
I tried to encrypt with the OTP (One Time Pad). I have coded a "test"-code to see if I make everything right, or not.
final String message = "Hello";
char character;
String binary;
for (int i = 0; i < message.length(); i++) {
character = message.charAt(i);
binary = Integer.toBinaryString(character);
System.out.println(character + ": " + binary);
}
So, there are the following:
H: 1001000
e: 1100101
l: 1101100
l: 1101100
o: 1101111
That is not really correct. I've searched in the inet, for example, the binary of H
01001000
There is one "0" missing. How can i fix this?
Instead of binary = Integer.toBinaryString(character);
use the following expression:
binary = String.format("%8s", Integer.toBinaryString(character)).replace(' ', '0');
The missing zeroes are leading zeroes. A binary representation is numerical in essence, which means leading zeroes have no meaning. Therefore they are left out; the number 01001000 equals the number 1001000.
If you do want to print these leading zeroes, I suggest you solve this by using a string formatting function, that prints an exact number of digits regardless of the number's length.
Another option would be using the DecimalFormat:
private static String format( Integer value, String format )
{
DecimalFormat myFormatter = new DecimalFormat( format );
return myFormatter.format( value );
}
With this you can just reach in the Number and the format in which it should be displayed. Like this:
System.out.println(format( 1001000 , "00000000" ));
With 0 as format you say the number 0 has to displayed or the number that is reached in. Meaning if your format is longer than the actual number the leading places will be displayed as 0.
If you read the JavaDoc you will find the section
Special Pattern Characters
There you can see an overview of the options for your format and what they will do.
EDIT:
As Olivier pointed out in the comments it is needed to convert it again.
When you convert your Character with Integer.toBinaryString(character);
you can just cast the String back to Long with Long.valueOf() and then reach it into to function or just refactor the method to:
private static String format( String value, String format )
{
DecimalFormat myFormatter = new DecimalFormat( format );
return myFormatter.format( Long.valueOf(value) );
}

Java - Construct a signed numeric String and convert it to an integer

Can I somehow prepend a minus sign to a numeric String and convert it into an int?
In example:
If I have 2 Strings :
String x="-";
String y="2";
how can i get them converted to an Int which value is -2?
You will first have to concatenate both Strings since - is not a valid integer character an sich. It is however acceptable when it's used together with an integer value to denote a negative value.
Therefore this will print -2 the way you want it:
String x = "-";
String y = "2";
int i = Integer.parseInt(x + y);
System.out.println(i);
Note that the x + y is used to concatenate 2 Strings and not an arithmetic operation.
Integer.valueOf("-") will throw a NumberFormatException because "-" by itself isn't a number. If you did "-1", however, you would receive the expected value of -1.
If you're trying to get a character code, use the following:
(int) "-".charAt(0);
charAt() returns a char value at a specific index, which is a two-byte unicode value that is, for all intensive purposes, an integer.

Categories

Resources