This question already has answers here:
Left padding a String with Zeros [duplicate]
(20 answers)
Closed 5 years ago.
How do I format a parsed String?
For example:
ph = "0412456839";
n = Long.parseLong(ph);
When I print n, I get (Without 0):
412456839
I want to print the same as ph. I could always do
System.out.println("0"+n);
but is there a way to format it?
Using java.util.Formatter
System.out.printf("%010d\n", n);
% 0 10 d
^ ^ ^
| | decimal
| width
zero-pad
If you need the output in a String instead of writing to System.out, use
String s = String.format("%010d", n);
You could create a DecimalFormat. That would allow you to format a number into a string using your own formatting rules. In this case, it is formatting it to be a 10 digit number that includes preceding zeros.
String ph = "0412456839";
Long n = Long.parseLong(ph);
String formattedN = new DecimalFormat("0000000000").format(n);
System.out.println(formattedN);
if you are using Apache Commons, you can use:
int paddingLength = 10;
String paddingCharacter = "0";
StringUtils.leftPad("" + n, paddingLength, paddingCharacter);
Related
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 2 years ago.
I want to get a user input using a JOptionPane input box and split the user's input into 2 sections. (I'm a student so I have to use JOptionPane.)
For example, I want to get the start time, 20:54, and split it to
startHour = 20;
startMin = 54;
you can use the split function of String class which return an array of string values then index 0 contain the hour, index 1 contain the minutes:
note: you need to cast the string value to int
String value = "20:54";
String [] parts = value.split(":");
int startHour = Integer.parseInt(parts[0]);
int startMin = Integer.parseInt(parts[1]);
This question already has answers here:
How to Convert an int to a String? [duplicate]
(6 answers)
Closed 8 years ago.
I'm trying to create a method which generates a 4 digit integer and stores it in a string.
The 4 digit integer must lie between 1000 and below 10000. Then the value must be stored to PINString.
Heres what I have so far. I get the error Cannot invoke toString(String) on the primitive type int. How can I fix it?
public void generatePIN()
{
//generate a 4 digit integer 1000 <10000
int randomPIN = (int)(Math.random()*9000)+1000;
//Store integer in a string
randomPIN.toString(PINString);
}
You want to use PINString = String.valueOf(randomPIN);
Make a String variable, concat the generated int value in it:
int randomPIN = (int)(Math.random()*9000)+1000;
String val = ""+randomPIN;
OR even more simple
String val = ""+((int)(Math.random()*9000)+1000);
Can't get any more simple than this ;)
randomPIN is a primitive datatype.
If you want to store the integer value in a String, use String.valueOf:
String pin = String.valueOf(randomPIN);
Use a string to store the value:
String PINString= String.valueOf(randomPIN);
Try this approach. The x is just the first digit. It is from 1 to 9.
Then you append it to another number which has at most 3 digits.
public String generatePIN()
{
int x = (int)(Math.random() * 9);
x = x + 1;
String randomPIN = (x + "") + ( ((int)(Math.random()*1000)) + "" );
return randomPIN;
}
This question already has answers here:
Print an integer in binary format in Java
(24 answers)
Closed 9 years ago.
How to get all 64 bits of a long as a String in Java?
So I want to do something like this -
long value = 10;
String bits = getBits(value);
System.out.println(bits);
I suppose the output would be
0000...1010 (64 bits)
And no, this is not homework! :)
Use Long.toString with the radix:
String bits = Long.toString(someLong, 2);
2 specifies binary as opposed to any other base.
Edit: If you want to left-pad:
String bits = Long.toString(someLong, 2);
StringBuilder sb = new StringBuilder();
for (int toPrepend=10-str.length(); toPrepend>0; toPrepend--) {
sb.append('0');
}
sb.append(bits);
String output = sb.toString();
You can call the method for it:
Long.toBinaryString(long number)
This question already has answers here:
Formatting a String to Remove Scientific Notation - Java
(4 answers)
Closed 9 years ago.
I'm trying to convert a HEX string into float from a data that comes from a device:
The device output in the LCD display,
0x00ac and the corresponding float value is 5.06
The method that calculated the value is:
final byte[] temp = new byte[1];
temp[0] = ba[0];
float fff = hexToFloat(bytesToHex(temp)).floatValue();
final float ff = ( fff / 42) * 1000;
String floatString = Float.toString(ff);
However the floatString output string contains "E-" notation. I need to remove this. Also it seems that the value of ff is slightly different from what the device output in the LCD.
I don't see how 0x00ac can be equal to 5.06, but here is how to get rid of the scientific notation with BigDecimals:
BigDecimal num = new BigDecimal(fltInput);
String numWithNoExponents = num.toPlainString()
This question already has answers here:
How can I pad an integer with zeros on the left?
(18 answers)
Closed 8 years ago.
Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)
static String intToString(int num, int digits) {
StringBuffer s = new StringBuffer(digits);
int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1;
for (int i = 0; i < zeroes; i++) {
s.append(0);
}
return s.append(num).toString();
}
String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)
In your case it will be:
String formatted = String.format("%03d", num);
0 - to pad with zeros
3 - to set width to 3
Since Java 1.5 you can use the String.format method. For example, to do the same thing as your example:
String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;
In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:
%% --> %
0 --> 0
%d --> <value of digits>
d --> d
So if digits is equal to 5, the format string becomes %05d which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format for more information on the conversion specifiers.
Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:
static String intToString(int num, int digits) {
assert digits > 0 : "Invalid number of digits";
// create variable length array of zeros
char[] zeros = new char[digits];
Arrays.fill(zeros, '0');
// format number as String
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
return df.format(num);
}
How about just:
public static String intToString(int num, int digits) {
String output = Integer.toString(num);
while (output.length() < digits) output = "0" + output;
return output;
}
In case of your jdk version less than 1.5, following option can be used.
int iTest = 2;
StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
sTest.append(String.valueOf(iTest));
System.out.println(sTest.substring(sTest.length()-6, sTest.length()));