Arbitrary radix padded format - java

I wonder if there's a standard way in Java to format an integer number into an arbitrary radix with left-padded zeroes.
E.g. for radix-32, padded to 4 characters length, if I have a number 30, I'd like to get a string like "000t" or if I have 300 I should get "008z" (t and 8z not necessarily correspond to base-32 notation of 30 and 300, it's just an example).

Convert the integer to a string in the radix that you need, then use the string formatter to pad the output string. The string formatter will pad with spaces, which you then need to convert to zeros.
Here's an example:
int num = 300;
String numString = Integer.toString(num, 30);
String padded = String.format("%1$#4s", numString).replace(' ', '0'); // "00ao"
The second argument to toString is the radix: 30 in this case.
The first argument to String.format is the format string, which I took from here. The value you care most about is the 4 in the middle of string: that's the total number of characters that you want in the string.

Related

How to format 18 digit double to become 10 string character

double pdouble= 3.3603335204002837E12;
String pstart= Double.toString(pdouble).replace(".", "") .trim()
String.format("%10d", pstart);
System.out.println("pstart"+pstart);
Can I know why it not works...
It display this:
Exception in thread "main"
java.util.IllegalFormatConversionException: d != java.lang.String at
java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
.I
Hope anybody can help
%d is for int. As pstart is a String, Use b or s.
String.format("%10s", pstart);
Output
33603335204002837E12
Read Java String format()
However if you need only the first 10 digits from your number, try using DecimalFormat
DecimalFormat d = new DecimalFormat("0000000000");
String number = d.format(pdouble);
Output
3360333520400
This will also add leading 0s if the number is less than 10 digits.
For decimal numbers "f" flag needs to be used.
double pdouble= 3.3603335204002837E12;
System.out.println(String.format("%10f", pdouble));
This will print a string with minimum length of 10 chars.
In this pattern "%10f" the width flag (e.g. 10) is the minimum number of characters
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.
from Formatter java doc

How to print formatted double value to string in java?

I want to create a String from a double value with 10 character for example
Double d = 150.23;
The output string like this 0000015023+
I have used this code but it is not working:
String imponibile = String.format("%10d%n", myDoubleValue);
You want to print 150.23 without the period. Formatting is not supposed to achieve that. You have to:
transform the double number to a int number with the desired rounding and print the int:
int i = (int) Math.round(100.0 * d);
String.format("%010d", i)
Where "010" means print at least 10 digits and pad with zero if there are less. The padding char going before the number of digits.
print the double and remove the period from the string afterwards:
String.format("%011.2f", d).replace(".", "")
Note how you now have to specify 11 including the period. And you have to specify the number of digits after the period
I don't think there is a way to print the sign after a number with String.format. You can easily require to print it at the start which is the normal way to print numbers:
String s = String.format("%+010d", i);
And if you must you can use substring and concatenation to put it at the end:
String imponibile = s.substring(1) + s.charAt(0);
Try f instead of d:
String imponibile = String.format("%010.0f", myDoubleValue*100);
Floating Point - may be applied to Java floating-point types: float,
Float, double, Double, and BigDecimal
Class Formatter

Java - Padding an integer

Well, I have a string in my Java code that needs to be converted into an integer with padding of 10.
Ex. Consider this is the string... Str = "52112"
I need to convert this string into an integer and the result should be like "0000052112". The result should be an integer. Can anyone help me with this, please?
As far as I know you cannot have an integer typed variable with leading zeros. You can pad the number with zeros but then it will become a String.
Take a look at:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#leftPad(java.lang.String,%20int)
In order to conform to the signature you have to convert the number to a string first, but that is no great deal.
The leading zeroes have no meaning if the data type you require is an Integer (or any other numeric type). If on the other hand you need a String with leading zeroes, you can use this (works only if required string length is >= number of digits of the number you want to pad) :
String myNumber = Integer.toString(42);
String myNumberWithLeadingZeroes = "0000000000" + myNumber;
// 10 zeroes if you need a string of length 10 in the end
myNumberWithLeadingZeroes = myNumberWithLeadingZeroes.substring(myNumber.length());

how to add digits in a long variable that will be converted to string?

i had this method:
public long getLastSequenceNumber();
it should return me:
0
a number that should be like 34,60,103...
the maximum amount of 12 digits number (243265438564 for example).
What i want is when i get this number i want to convert it to a String and add the "0" that is missing in the front of number to get the 12 digits. if it comes with 12 digits then just convert to string.
Example:
if i get 45 then convert to "000000000045".
if i get 0 then convert to "000000000000".
if i get 834213238956l (12 digits) then just convert to
"834213238956" (same number, but in String).
How i can do it in Java?
You can use a DecimalFormat to convert the number directly to a String.
DecimalFormat df = new DecimalFormat("000000000000"); // 12 zeros
String s = df.format(x);
String fortyFive = df.format(45);
Alternatively, you can call String.format with a 0 to indicate leading zeros and a 12 for the length.
String s = String.format("%012d", x);
String fortyFive = String.format("%012d", 45);

Java display length of int containing leading zeros

I want to display the length of a 4-digit number displayed by the user, the problem that I'm running into is that whenever I read the length of a number that is 4-digits long but has trailing zeros the length comes to the number of digits minus the zeros.
Here is what I tried:
//length of values from number input
int number = 0123;
int length = (int)Math.log10(number) + 1;
This returns to length of 3
The other thing I tried was:
int number = 0123;
int length = String.valueOf(number).length();
This also returned a length of 3.
Are there any alternatives to how I can obtain this length?
Because int number = 0123 is the equivalent of int number = 83 as 0123 is an octal constant. Thanks to #DavidConrad and #DrewKennedy for the octal precision.
Instead declare it as a String if you want to keep the leading 0
String number = "0123";
int length = number.length();
And then when you need the number, simply do Integer.parseInt(number)
Why is the syntax of octal notation in java 0xx ?
Java syntax was designed to be close to that of C, see eg page 20 at
How The JVM Spec Came To Be keynote from the JVM Languages Summit 2008
by James Gosling (20_Gosling_keynote.pdf):
In turn, this is the way how octal constants are defined in C language:
If an integer constant begins with 0x or 0X, it is hexadecimal. If it
begins with the digit 0, it is octal. Otherwise, it is assumed to be
decimal...
Note that this part is a C&P of #gnat answer on programmers.stackexchange.
https://softwareengineering.stackexchange.com/questions/221797/reasoning-behind-the-syntax-of-octal-notation-in-java
Use a string instead:
String number = "0123";
int length = number.length(); // equals 4
This doesn't work with an int, as the internal representation of 0123 is identical to 123. The program doesn't remember how the value was written, only the actual value.
What you can do is declare a string:
String number = "0123";
int numberLengthWithLeadingZeroes = number.length(); // == 4
int numberValue = Integer.parseInt(number); // == 123
If you really want to include leading 0's you could always store it in an array of of characters
example:
char[] abc = String.valueOf(number).toCharArray();
Then obviously you can figure out the length of the array.
As several people have pointed out already though, integers don't have leading 0's.
String abc=String.format("%04d", yournumber);
for zero-padding with length=4.
Refer to this link .
http://download.oracle.com/javase/7/docs/api/java/util/Formatter.html
this might help u ..
Integers in Java don't have leading zeroes. If you assign the value 0123 to your int or Integer variable, it will be interpreted as an octal constant rather than a decimal one, which can lead to subtle bugs.
Instead, if you want to keep leading zeroes, use a String, e.g.
String number = "0123";
This way you can also measure the length:
String number = "0123";
System.out.println(number.length());

Categories