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);
Related
For example, I would like to convert the int value 12 into a String output of BCD: 00 12 (0x00 0x12).
If I have int value of 256, it will be 02 56 (which is 0x02 0x56),
or if I have a int value of 999, it will be 09 99 (0x09 0x99),
9999 would be 99 99 (0x99 0x99).
Right now, my only solution is to create a String array of size 4, and calculate how many characters are there by converting the int value into String. If there are 2 characters, I will add 2 x 0 into the array first before adding the 2 characters, and then make them back into a single String variable.
Basically,
int value = 12;
String output = Integer.toString(value);
// then count the number of characters in the String.
// 4 minus (whatever number of characters in the String, add zeros
// add the characters:
stringArray[0] = "0";
stringArray[1] = "0";
stringArray[2] = "1";
stringArray[3] = "2";
// then, concatenate them back
If there are 3 characters, I will add one 0 into the array first before adding 3 characters. I was wondering if there is any other way?
You can use String.format to append leading 0 and use substring to split in to two part.
int value = 12;
String output = String.format("%04d",value);
System.out.println(output.substring(0,2)+" "+output.substring(2,4));
String.format("%04d",value) will append 0s in the front if the length is less than 4.
If you do not want to use substring you can use String.split and String.join like below.
System.out.println(
String.join(
" ",
Arrays.asList(
output.split("(?<=\\G.{2})")
)
)
);
output.split("(?<=\\G.{2})") will split the string in 2 characters each.
Is that what you are asking for?
public static String formatTheString(String string, int length) {
return String.format("%"+length+"s", string).replace(' ', '0');
}
and pass the values like
formatTheString(Integer.toString(256),4);
I think what you are asking is not correct.
refer this for BCD.
and below code is sufficient for what you need
System.out.printf("%04d",n);
in above code n is your number.
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.
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) );
}
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).
I have following string in my java class
String str="0000000000008";
Now I want to increment that so that the next value should be 0000000000009
For that purpose, I tried to cast this String str into Integer
Integer i=Integer.parseFloat(str)+1;
and when I print the value of i it prints only 17(as it removes the leading 0's from string at the time of cast).
How can I increment the String value, so that the leading 0's will remain, and the series will continue?
Practical solution - use String.format:
str = String.format("%013d", Long.parseLong(str)+1);
You are on the correct path. First parse to Long:
long cur = Long.parseLong("0000000000008");
increment and format back to String with leading 0s:
new java.text.DecimalFormat("0000000000000").format(cur + 1);
or alternatively:
String.format("%013d", Long.valueOf(cur));