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()));
Related
The following code:
String a = "100.00";
String b = "10.00";
String c= "5.00";
String value = a+ "\n"+ b +"\n" +c;
System.out.println(value);
Prints:
100.00
10.00
5.00
I need output in a format where decimal point position will be fixed without using any string format library (with logic):
100.00
10.00
5.00
Variable values are coming from the database and requirement is to show values with the decimal point in the same position with values vertically.
Here's an example using streams; probably could be more efficient but I was having fun.
It assumes all have 2 decimals as you showed, just FYI; that could be modified though.
String a = "100.00";
String b = "10.00";
String c= "5.00";
List<String> strings = Arrays.asList(a, b, c);
final int maxLen = strings.stream().map(String::length).reduce(Math::max).get();
strings.forEach(s -> {
System.out.println(Stream.generate(() -> " ").limit(maxLen - s.length()).collect(Collectors.joining()) + s);
});
Results:
100.00
10.00
5.00
I also put pthe 3 examples into a list so it would work on an arbitrary number of elements.
Without Java 8
String a = "100.00";
String b = "10.00";
String c = "5.00";
List<String> strings = Arrays.asList(a, b, c);
int maxLen = -1;
for (String s : strings) maxLen = Math.max(maxLen, s.length());
for (String s : strings) {
String spaces = "";
for (int i = 0; i < maxLen - s.length(); ++i) {
spaces += " ";
}
System.out.println(spaces += s);
}
I don't know what 'don't use any String format library' means specifically, but... now we get into a semantic argument as to what 'library' means. You're formatting a string. If I take your question on face value you're asking for literally the impossible: How does one format a string without formatting a string?
I'm going to assume you meant: Without adding a third party dependency.
In which case, if you have doubles (or BigDecimal or float) as input:
String.format("%6.2f", 100.00);
String.format("%6.2f", 10.00);
String.format("%6.2f", 5.00);
(6? Yes; 6! The 6 is the total # of characters to print at minimum. You want 3 digits before the separator, a separator, and 2 digits after, that's a grand total of 6, hence the 6.)
If you have strings as input, evidently you are asking to right-justify them? Well, you can do that:
String.format("%6s", "100.00");
String.format("%6s", "10.00");
String.format("%6s", "5.00");
NB: For convenience, System.out.printf("%6s\n", "100.0"); is short for System.out.println(String.format("%6s", "100.0"));
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);
Below is a snippet of my java code.
//converts a binary string to hexadecimal
public static String binaryToHex (String binaryNumber)
{
BigInteger temp = new BigInteger(binaryNumber, 2);
return temp.toString(16).toUpperCase();
}
If I input "0000 1001 0101 0111" (without the spaces) as my String binaryNumber, the return value is 957. But ideally what I want is 0957 instead of just 957. How do I make sure to pad with zeroes if hex number is not 4 digits?
Thanks.
You do one of the following:
Manually pad with zeroes
Use String.format()
Manually pad with zeroes
Since you want extra leading zeroes when shorter than 4 digits, use this:
BigInteger temp = new BigInteger(binaryNumber, 2);
String hex = temp.toString(16).toUpperCase();
if (hex.length() < 4)
hex = "000".substring(hex.length() - 1) + hex;
return hex;
Use String.format()
BigInteger temp = new BigInteger(binaryNumber, 2);
return String.format("%04X", temp);
Note, if you're only expecting the value to be 4 hex digits long, then a regular int can hold the value. No need to use BigInteger.
In Java 8, do it by parsing the binary input as an unsigned number:
int temp = Integer.parseUnsignedInt(binaryNumber, 2);
return String.format("%04X", temp);
The BigInteger becomes an internal machine representation of whatever value you passed in as a String in binary format. Therefore, the machine does not know how many leading zeros you would like in the output format. Unfortunately, the method toString in BigInteger does not allow any kind of formatting, so you would have to do it manually if you attempt to use the code you showed.
I customized your code a bit to include leading zeros based on input string:
public static void main(String[] args) {
System.out.println(binaryToHex("0000100101010111"));
}
public static String binaryToHex(String binaryNumber) {
BigInteger temp = new BigInteger(binaryNumber, 2);
String hexStr = temp.toString(16).toUpperCase();
int b16inLen = binaryNumber.length()/4;
int b16outLen = hexStr.length();
int b16padding = b16inLen - b16outLen;
for (int i=0; i<b16padding; i++) {
hexStr=('0'+hexStr);
}
return hexStr;
}
Notice that the above solution counts up the base16 digits in the input and calculates the difference with the base16 digits in the output. So, it requires the user to input a full '0000' to be counted up. That is '000 1111' will be displayed as 'F' while '0000 1111' as '0F'.
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;
}
What I want to do is getting the first 2 digits of a number. If number hasn't digits more than 1 then It will add leading zeros.
s variable equals to "122" but I want to get first 2 digits which are "12". I think there is a problem with my format.
for example if totalNumberOfCars equals 6 then s variable will equals to "06".
int totalNumberOfCars = 122;
String s = String.format("%02d", (totalNumberOfCars + 1))
EDIT: Is there anyone knows what String.format("%02d", totalNumberOfCars) does?
I'm afraid that String.format() won't do the job, see http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax.
But your format string will be a good starting point for a substring since any ifs are unnecessary:
int totalNumberOfCars = 122;
String s = String.format("%02d", (totalNumberOfCars + 1));
s = s.substring(0,2);
By the way the condensed explaination from the javadoc link above:
The format specifiers which do not correspond to arguments have the following syntax:
%[flags][width]conversion
[...] further down on the same page:
Flags
'0' [...] [means] zero-padded
[...] further down on the same page:
Width
The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.
Example output would be:
1 --> 01
-1 --> -1
10 --> 10
122--> 122
Maybe not very elegant, but it should work:
String s = ((totalNumberOfCars<10?"0":"")+totalNumberOfCars).substring(0,2);
String s = substring_safe (s, 0, 2);
static String substring_safe (String s, int start, int len) { ... }
which will check lengths beforehand and act accordingly (either return smaller string or pad with spaces).