Java: How to format String number with tenth exponent - java

I have a number as a string like this: "9.756088256835938E-4" but I only can use a specified number of characters (in this special case 9 char). So I want to have something like this: "9.7561E-4". I already tried to convert the String to a Double and then used the format method to get a less characters but I don't got a correct solution.
The problem is that I need ten exponential output since some numbers are longer than the number of characters I have. If it is possible, the number should be displayed with no ten exponent, if not just use the ten exponent.
Also correct rounding would be good.
And it should work for negative numbers. (minus needs one character!!!)
Is there a format function where I can define the maximum length of the output string? Any ideas?

I'm having trouble findind a single format pattern that will cover all of the cases that you described. But here's a combination of logic that I think works:
public static void main(String[] args) throws Exception {
// 97.560883
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+1")));
// 9.756E+11
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+11")));
// 0.0009756
System.out.println(formatNum(Double.parseDouble("9.756088256835938E-4")));
// -9.8E+111
System.out.println(formatNum(Double.parseDouble("-9.756088256835938E+111")));
}
private static final int MAX_LENGTH = 9;
private static String formatNum(double number) {
String out = null;
for ( int i = 0; i < MAX_LENGTH; i++ ) {
String format = "%." + i + "G";
out = String.format(format, number);
if ( out.length() == MAX_LENGTH ) {
return out;
}
}
return out; //the best we can do
}
The "G" in the pattern instructs the formatter to forego the use of the exponent when it will allow for the same or better precision. We grow up to the maximum length and stop when our output string is 10 characters. I think you could take the same approach with a DecimalFormat, but I'm more familiar with Formatter.

Seeing the Mark's example meet your requirements, I updated my answer to show the DecimalFormat implementation. I used Mark's test cases. It is definitely an uglier option because there is no easy way to turn on/off exponents. The only advantage over the String.format option is that it handles very small numbers well.
public static void main(String[] args) throws Exception {
// 97.560883
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+1")));
// 9.756E+11
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+11")));
// 0.0009756
System.out.println(formatNum(Double.parseDouble("9.756088256835938E-4")));
// -9.8E+111
System.out.println(formatNum(Double.parseDouble("-9.756088256835938E+111")));
}
private static final int MAX_LENGTH = 9;
private static String formatNum(double number) {
int digitsAvailable = MAX_LENGTH - 2;
if (Math.abs(number) < Math.pow(10, digitsAvailable)
&& Math.abs(number) > Math.pow(10, -digitsAvailable)) {
String format = "0.";
double temp = number;
for (int i = 0; i < digitsAvailable; i++) {
if ((temp /= 10) < 1) {
format += "#";
}
}
return new DecimalFormat(format).format(number);
}
String format = "0.";
for (int i = 0; i < digitsAvailable; i++) {
format += "#";
}
String r = new DecimalFormat(format + "E0").format(number);
int lastLength = r.length() + 1;
while (r.length() > MAX_LENGTH && lastLength > r.length()) {
lastLength = r.length();
r = r.replaceAll("\\.?[0-9]E", "E");
}
return r;
}
This reminded me of a similar question where the OP only had 5 or so spaces for a number and wanted to show a decimal only when there was enough space. But instead of exponents, wanted to use a suffix of (k,m, etc)

Related

What is the safest way to complete String digits with zeros in Java? [duplicate]

How do you left pad an int with zeros when converting to a String in java?
I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).
Use java.lang.String.format(String,Object...) like this:
String.format("%05d", yournumber);
for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".
The full formatting options are documented as part of java.util.Formatter.
Let's say you want to print 11 as 011
You could use a formatter: "%03d".
You can use this formatter like this:
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
Alternatively, some java methods directly support these formatters:
System.out.printf("%03d", a);
If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method
org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
Found this example... Will test...
import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
public static void main(String [] args)
{
int x=1;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(x));
}
}
Tested this and:
String.format("%05d",number);
Both work, for my purposes I think String.Format is better and more succinct.
Try this one:
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // Output: 0009
String a = df.format(99); // Output: 0099
String b = df.format(999); // Output: 0999
If performance is important in your case you could do it yourself with less overhead compared to the String.format function:
/**
* #param in The integer value
* #param fill The number of digits to fill
* #return The given value left padded with the given number of digits
*/
public static String lPadZero(int in, int fill){
boolean negative = false;
int value, len = 0;
if(in >= 0){
value = in;
} else {
negative = true;
value = - in;
in = - in;
len ++;
}
if(value == 0){
len = 1;
} else{
for(; value != 0; len ++){
value /= 10;
}
}
StringBuilder sb = new StringBuilder();
if(negative){
sb.append('-');
}
for(int i = fill; i > len; i--){
sb.append('0');
}
sb.append(in);
return sb.toString();
}
Performance
public static void main(String[] args) {
Random rdm;
long start;
// Using own function
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
lPadZero(rdm.nextInt(20000) - 10000, 4);
}
System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");
// Using String.format
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
String.format("%04d", rdm.nextInt(20000) - 10000);
}
System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}
Result
Own function: 1697ms
String.format: 38134ms
Here is how you can format your string without using DecimalFormat.
String.format("%02d", 9)
09
String.format("%03d", 19)
019
String.format("%04d", 119)
0119
You can use Google Guava:
Maven:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
Sample code:
String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
Note:
Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc
Ref: GuavaExplained
Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.
import java.text.NumberFormat;
public class NumberFormatMain {
public static void main(String[] args) {
int intNumber = 25;
float floatNumber = 25.546f;
NumberFormat format=NumberFormat.getInstance();
format.setMaximumIntegerDigits(6);
format.setMaximumFractionDigits(6);
format.setMinimumFractionDigits(6);
format.setMinimumIntegerDigits(6);
System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));
System.out.println("Formatted Float : "+format.format(floatNumber).replace(",",""));
}
}
int x = 1;
System.out.format("%05d",x);
if you want to print the formatted text directly onto the screen.
You need to use a Formatter, following code uses NumberFormat
int inputNo = 1;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumIntegerDigits(4);
nf.setMinimumIntegerDigits(4);
nf.setGroupingUsed(false);
System.out.println("Formatted Integer : " + nf.format(inputNo));
Output: 0001
Use the class DecimalFormat, like so:
NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811));
OUTPUT : 0000811
You can add leading 0 to your string like this. Define a string that will be the maximum length of the string that you want. In my case i need a string that will be only 9 char long.
String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);
Output : 000602939
Check my code that will work for integer and String.
Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code
int number=2;
int requiredLengthAfterPadding=4;
String resultString=Integer.toString(number);
int inputStringLengh=resultString.length();
int diff=requiredLengthAfterPadding-inputStringLengh;
if(inputStringLengh<requiredLengthAfterPadding)
{
resultString=new String(new char[diff]).replace("\0", "0")+number;
}
System.out.println(resultString);
Use this simple extension function
fun Int.padZero(): String {
return if (this < 10) {
"0$this"
} else {
this.toString()
}
}
For Kotlin
fun Calendar.getFullDate(): String {
val mYear = "${this.get(Calendar.YEAR)}-"
val mMonth = if (this.get(Calendar.MONTH) + 1 < 10) {
"0${this.get(Calendar.MONTH) + 1}-"
} else {
"${this.get(Calendar.MONTH)+ 1}-"
}
val mDate = if (this.get(Calendar.DAY_OF_MONTH) < 10) {
"0${this.get(Calendar.DAY_OF_MONTH)}"
} else {
"${this.get(Calendar.DAY_OF_MONTH)}"
}
return mYear + mMonth + mDate
}
and use it as
val date: String = calendar.getFullDate()
Here is another way to pad an integer with zeros on the left. You can increase the number of zeros as per your convenience. Have added a check to return the same value as is in case of negative number or a value greater than or equals to zeros configured. You can further modify as per your requirement.
/**
*
* #author Dinesh.Lomte
*
*/
public class AddLeadingZerosToNum {
/**
*
* #param args
*/
public static void main(String[] args) {
System.out.println(getLeadingZerosToNum(0));
System.out.println(getLeadingZerosToNum(7));
System.out.println(getLeadingZerosToNum(13));
System.out.println(getLeadingZerosToNum(713));
System.out.println(getLeadingZerosToNum(7013));
System.out.println(getLeadingZerosToNum(9999));
}
/**
*
* #param num
* #return
*/
private static String getLeadingZerosToNum(int num) {
// Initializing the string of zeros with required size
String zeros = new String("0000");
// Validating if num value is less then zero or if the length of number
// is greater then zeros configured to return the num value as is
if (num < 0 || String.valueOf(num).length() >= zeros.length()) {
return String.valueOf(num);
}
// Returning zeros in case if value is zero.
if (num == 0) {
return zeros;
}
return new StringBuilder(zeros.substring(0, zeros.length() -
String.valueOf(num).length())).append(
String.valueOf(num)).toString();
}
}
Input
0
7
13
713
7013
9999
Output
0000
0007
0013
7013
9999
No packages needed:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.

How to implement "String.format()" in Java? [duplicate]

How do you left pad an int with zeros when converting to a String in java?
I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).
Use java.lang.String.format(String,Object...) like this:
String.format("%05d", yournumber);
for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".
The full formatting options are documented as part of java.util.Formatter.
Let's say you want to print 11 as 011
You could use a formatter: "%03d".
You can use this formatter like this:
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
Alternatively, some java methods directly support these formatters:
System.out.printf("%03d", a);
If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method
org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
Found this example... Will test...
import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
public static void main(String [] args)
{
int x=1;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(x));
}
}
Tested this and:
String.format("%05d",number);
Both work, for my purposes I think String.Format is better and more succinct.
Try this one:
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // Output: 0009
String a = df.format(99); // Output: 0099
String b = df.format(999); // Output: 0999
If performance is important in your case you could do it yourself with less overhead compared to the String.format function:
/**
* #param in The integer value
* #param fill The number of digits to fill
* #return The given value left padded with the given number of digits
*/
public static String lPadZero(int in, int fill){
boolean negative = false;
int value, len = 0;
if(in >= 0){
value = in;
} else {
negative = true;
value = - in;
in = - in;
len ++;
}
if(value == 0){
len = 1;
} else{
for(; value != 0; len ++){
value /= 10;
}
}
StringBuilder sb = new StringBuilder();
if(negative){
sb.append('-');
}
for(int i = fill; i > len; i--){
sb.append('0');
}
sb.append(in);
return sb.toString();
}
Performance
public static void main(String[] args) {
Random rdm;
long start;
// Using own function
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
lPadZero(rdm.nextInt(20000) - 10000, 4);
}
System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");
// Using String.format
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
String.format("%04d", rdm.nextInt(20000) - 10000);
}
System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}
Result
Own function: 1697ms
String.format: 38134ms
Here is how you can format your string without using DecimalFormat.
String.format("%02d", 9)
09
String.format("%03d", 19)
019
String.format("%04d", 119)
0119
You can use Google Guava:
Maven:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
Sample code:
String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
Note:
Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc
Ref: GuavaExplained
Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.
import java.text.NumberFormat;
public class NumberFormatMain {
public static void main(String[] args) {
int intNumber = 25;
float floatNumber = 25.546f;
NumberFormat format=NumberFormat.getInstance();
format.setMaximumIntegerDigits(6);
format.setMaximumFractionDigits(6);
format.setMinimumFractionDigits(6);
format.setMinimumIntegerDigits(6);
System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));
System.out.println("Formatted Float : "+format.format(floatNumber).replace(",",""));
}
}
int x = 1;
System.out.format("%05d",x);
if you want to print the formatted text directly onto the screen.
You need to use a Formatter, following code uses NumberFormat
int inputNo = 1;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumIntegerDigits(4);
nf.setMinimumIntegerDigits(4);
nf.setGroupingUsed(false);
System.out.println("Formatted Integer : " + nf.format(inputNo));
Output: 0001
Use the class DecimalFormat, like so:
NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811));
OUTPUT : 0000811
You can add leading 0 to your string like this. Define a string that will be the maximum length of the string that you want. In my case i need a string that will be only 9 char long.
String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);
Output : 000602939
Check my code that will work for integer and String.
Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code
int number=2;
int requiredLengthAfterPadding=4;
String resultString=Integer.toString(number);
int inputStringLengh=resultString.length();
int diff=requiredLengthAfterPadding-inputStringLengh;
if(inputStringLengh<requiredLengthAfterPadding)
{
resultString=new String(new char[diff]).replace("\0", "0")+number;
}
System.out.println(resultString);
Use this simple extension function
fun Int.padZero(): String {
return if (this < 10) {
"0$this"
} else {
this.toString()
}
}
For Kotlin
fun Calendar.getFullDate(): String {
val mYear = "${this.get(Calendar.YEAR)}-"
val mMonth = if (this.get(Calendar.MONTH) + 1 < 10) {
"0${this.get(Calendar.MONTH) + 1}-"
} else {
"${this.get(Calendar.MONTH)+ 1}-"
}
val mDate = if (this.get(Calendar.DAY_OF_MONTH) < 10) {
"0${this.get(Calendar.DAY_OF_MONTH)}"
} else {
"${this.get(Calendar.DAY_OF_MONTH)}"
}
return mYear + mMonth + mDate
}
and use it as
val date: String = calendar.getFullDate()
Here is another way to pad an integer with zeros on the left. You can increase the number of zeros as per your convenience. Have added a check to return the same value as is in case of negative number or a value greater than or equals to zeros configured. You can further modify as per your requirement.
/**
*
* #author Dinesh.Lomte
*
*/
public class AddLeadingZerosToNum {
/**
*
* #param args
*/
public static void main(String[] args) {
System.out.println(getLeadingZerosToNum(0));
System.out.println(getLeadingZerosToNum(7));
System.out.println(getLeadingZerosToNum(13));
System.out.println(getLeadingZerosToNum(713));
System.out.println(getLeadingZerosToNum(7013));
System.out.println(getLeadingZerosToNum(9999));
}
/**
*
* #param num
* #return
*/
private static String getLeadingZerosToNum(int num) {
// Initializing the string of zeros with required size
String zeros = new String("0000");
// Validating if num value is less then zero or if the length of number
// is greater then zeros configured to return the num value as is
if (num < 0 || String.valueOf(num).length() >= zeros.length()) {
return String.valueOf(num);
}
// Returning zeros in case if value is zero.
if (num == 0) {
return zeros;
}
return new StringBuilder(zeros.substring(0, zeros.length() -
String.valueOf(num).length())).append(
String.valueOf(num)).toString();
}
}
Input
0
7
13
713
7013
9999
Output
0000
0007
0013
7013
9999
No packages needed:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.

Java read integer from middle of the string

Is it possible in Java to efficiently read an integer from random position of the string? For instance, I have a
String s = "(34";
if (s.charAt(0) == '(')
{
// How to read a number from position = 1 to the end of the string?
// Of course, I can do something like
String s1 = s.substring(1);
int val = Integer.parseInt(s1);
}
but it dynamically creates a new instance of string and seems to be too slow and performance hitting.
UPDATE
Well, to be precise: I have an array of strings in form "(ddd" where d is a digit. So I do know that a number starts always from pos = 1. How do I efficently read these numbers?
Integer.parseInt(s1.replaceAll("[\\D]", ""))
Answered before the update:
I'm not an expert in regex, but hope this "\\d+" is useful to you. Invoke the below method with pattern: "\\d+".
public static int returnInt(String pattern,String inputString){
Pattern intPattern = Pattern.compile(pattern);
Matcher matcher = intPattern.matcher(inputString);
matcher.find();
String input = matcher.group();
return Integer.parseInt(input);
}
Answered after the update:
String is a final object, you cannot edit it, so if you want to get some digit value from it, you have the 2 ways:
1. Use your code, that will work fine, but if you care about performance, try 2nd way.
2. Divide your string on digits and add them to get the result:
public static void main(String[] args) {
String input = "(123456";
if(input.charAt(0) == '(') {
System.out.println(getDigit(input));
}
}
private static int getDigit(String s) {
int result = 0;
int increase = 10;
for(int i = 1; i < s.length(); i++) {
int digit = Character.getNumericValue(s.charAt(i));
result*=increase;
result += digit;
}
return result;
}
Output:
123456
If you don't want to allocate a new String then you can use the code in this other SO answer:
int charArrayToInt(char[] data, int start, int end) throws NumberFormatException {
int result = 0;
for (int i = start; i < end; i++) {
int digit = ((int)data[i] & 0xF);
if ((digit < 0) || (digit > 9)) throw new NumberFormatException();
result *= 10;
result += digit;
}
return result;
}
You can call it with charArrayToInt(s.toCharArray(), 1, s.length())

Android - Convert Arch to Decimal

I'm creating a feet and inches calculator. I want the user to be able to enter the information in various ways such as 1'-4-5/8" or 1 4 5/8.
When performing math, the above numbers will have to be converted to decimal (1'-4-5/8" is 16.625 in decimal inches). The final result will be in either decimal inches or then converted back to feet and inches.
How would I go about parsing the architectural measurement and converting it into decimal inches?
Any help would be greatly appreciated!
Thank you!
edit:
After way too much time and trying many different things, I think I got something that will work. I'm ultimately going to limit the way the user can enter the length so I think the following is going to work. It may not be optimized but it's the best I can get right now.
public class delim_test_cases {
public static void main(String[] args) {
double inches = 0;
double feet = 0;
double fract = 0;
String str = "2'-3-7/8";
String[] TempStr;
String delimiter = ("[-]+");
TempStr = str.split(delimiter);
for(int i=0; i< TempStr.length ; i++ ) {
for(int z=0; z< TempStr[i].length() ; z++ ) {
if (TempStr[i].charAt(z) == '\'') {
String[] FeetStr;
String feetdelim = ("[\']+");
FeetStr = TempStr[i].split(feetdelim);
feet = Integer.parseInt(FeetStr[0]);
}
else if (TempStr[i].charAt(z) == '/') {
String[] FracStr;
String fracdelim = ("[/]+");
FracStr = TempStr[i].split(fracdelim);
double numer = Integer.parseInt(FracStr[0]);
double denom = Integer.parseInt(FracStr[1]);
fract = numer/denom;
}
else if (TempStr[i].indexOf("\'")==-1 && TempStr[i].indexOf("/")==-1) {
String inchStr;
inchStr = TempStr[i];
inches = Integer.parseInt(inchStr);
}
}
}
double answer = ((feet*12)+inches+fract);
System.out.println(feet);
System.out.println(inches);
System.out.println(fract);
System.out.println(answer);
}
}
Why not just split on either the '-' or a space, then you have an array of possibly 3 strings.
So, you look at the last character, if it is a single quote, then multiply that by 12.
If a double quote, then split on '/' and just calculate the fraction, and for a number that is neither of these it is an inch, just add it to the total.
This way you don't assume the order or what if you just have fractional inches.
Just loop through the array and then go through the algorithm above, so if someone did
3'-4'-4/2" then you can calculate it easily.
UPDATE:
I am adding code based on the comment from the OP.
You may want to refer to this to get more ideas about split.
http://www.java-examples.com/java-string-split-example
But, basically, just do something like this (not tested, just written out):
public double convertArchToDecimal(String instr, String delimiter) {
String[] s = instr.split(delimiter);
int ret = 0;
for(int t = 0; t < s.length; t++) {
char c = s[t].charAt(s[t] - length);
switch(c) {
case '\'': //escape single quote
String b = s[t].substring(0, s[t].length - 1).split("/");
try {
ret += Integer.parse(s[t].trim()) * 12;
} catch(Exception e) { // Should just need to catch if the parse throws an error
}
break;
case '"': // may need to escape the double quote
String b = s[t].substring(0, s[t].length - 1).split("/");
int f = 0;
int g = 0;
try {
f = Integer.parse(b[0]);
g = Integer.parse(b[1]);
ret += f/g;
} catch(Exception e) {
}
break;
default:
try {
ret += Integer.parse(s[t].trim());
} catch(Exception e) { // Should just need to catch if the parse throws an error
}
break;
}
}
return ret;
}
I am catching more exceptions than is needed, and you may want to use the trim() method more than I did, to strip whitespace before parsing, to protect against 3 / 5 " for example.
By passing in a space or dash it should suffice for your needs.
You may also want to round to some significant figures otherwise rounding may cause problems for you later.

How can I pad an integer with zeros on the left?

How do you left pad an int with zeros when converting to a String in java?
I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).
Use java.lang.String.format(String,Object...) like this:
String.format("%05d", yournumber);
for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".
The full formatting options are documented as part of java.util.Formatter.
Let's say you want to print 11 as 011
You could use a formatter: "%03d".
You can use this formatter like this:
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
Alternatively, some java methods directly support these formatters:
System.out.printf("%03d", a);
If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method
org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
Found this example... Will test...
import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
public static void main(String [] args)
{
int x=1;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(x));
}
}
Tested this and:
String.format("%05d",number);
Both work, for my purposes I think String.Format is better and more succinct.
Try this one:
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // Output: 0009
String a = df.format(99); // Output: 0099
String b = df.format(999); // Output: 0999
If performance is important in your case you could do it yourself with less overhead compared to the String.format function:
/**
* #param in The integer value
* #param fill The number of digits to fill
* #return The given value left padded with the given number of digits
*/
public static String lPadZero(int in, int fill){
boolean negative = false;
int value, len = 0;
if(in >= 0){
value = in;
} else {
negative = true;
value = - in;
in = - in;
len ++;
}
if(value == 0){
len = 1;
} else{
for(; value != 0; len ++){
value /= 10;
}
}
StringBuilder sb = new StringBuilder();
if(negative){
sb.append('-');
}
for(int i = fill; i > len; i--){
sb.append('0');
}
sb.append(in);
return sb.toString();
}
Performance
public static void main(String[] args) {
Random rdm;
long start;
// Using own function
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
lPadZero(rdm.nextInt(20000) - 10000, 4);
}
System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");
// Using String.format
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
String.format("%04d", rdm.nextInt(20000) - 10000);
}
System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}
Result
Own function: 1697ms
String.format: 38134ms
Here is how you can format your string without using DecimalFormat.
String.format("%02d", 9)
09
String.format("%03d", 19)
019
String.format("%04d", 119)
0119
You can use Google Guava:
Maven:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
Sample code:
String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
Note:
Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc
Ref: GuavaExplained
Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.
import java.text.NumberFormat;
public class NumberFormatMain {
public static void main(String[] args) {
int intNumber = 25;
float floatNumber = 25.546f;
NumberFormat format=NumberFormat.getInstance();
format.setMaximumIntegerDigits(6);
format.setMaximumFractionDigits(6);
format.setMinimumFractionDigits(6);
format.setMinimumIntegerDigits(6);
System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));
System.out.println("Formatted Float : "+format.format(floatNumber).replace(",",""));
}
}
int x = 1;
System.out.format("%05d",x);
if you want to print the formatted text directly onto the screen.
You need to use a Formatter, following code uses NumberFormat
int inputNo = 1;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumIntegerDigits(4);
nf.setMinimumIntegerDigits(4);
nf.setGroupingUsed(false);
System.out.println("Formatted Integer : " + nf.format(inputNo));
Output: 0001
Use the class DecimalFormat, like so:
NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811));
OUTPUT : 0000811
You can add leading 0 to your string like this. Define a string that will be the maximum length of the string that you want. In my case i need a string that will be only 9 char long.
String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);
Output : 000602939
Check my code that will work for integer and String.
Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code
int number=2;
int requiredLengthAfterPadding=4;
String resultString=Integer.toString(number);
int inputStringLengh=resultString.length();
int diff=requiredLengthAfterPadding-inputStringLengh;
if(inputStringLengh<requiredLengthAfterPadding)
{
resultString=new String(new char[diff]).replace("\0", "0")+number;
}
System.out.println(resultString);
Use this simple extension function
fun Int.padZero(): String {
return if (this < 10) {
"0$this"
} else {
this.toString()
}
}
For Kotlin
fun Calendar.getFullDate(): String {
val mYear = "${this.get(Calendar.YEAR)}-"
val mMonth = if (this.get(Calendar.MONTH) + 1 < 10) {
"0${this.get(Calendar.MONTH) + 1}-"
} else {
"${this.get(Calendar.MONTH)+ 1}-"
}
val mDate = if (this.get(Calendar.DAY_OF_MONTH) < 10) {
"0${this.get(Calendar.DAY_OF_MONTH)}"
} else {
"${this.get(Calendar.DAY_OF_MONTH)}"
}
return mYear + mMonth + mDate
}
and use it as
val date: String = calendar.getFullDate()
Here is another way to pad an integer with zeros on the left. You can increase the number of zeros as per your convenience. Have added a check to return the same value as is in case of negative number or a value greater than or equals to zeros configured. You can further modify as per your requirement.
/**
*
* #author Dinesh.Lomte
*
*/
public class AddLeadingZerosToNum {
/**
*
* #param args
*/
public static void main(String[] args) {
System.out.println(getLeadingZerosToNum(0));
System.out.println(getLeadingZerosToNum(7));
System.out.println(getLeadingZerosToNum(13));
System.out.println(getLeadingZerosToNum(713));
System.out.println(getLeadingZerosToNum(7013));
System.out.println(getLeadingZerosToNum(9999));
}
/**
*
* #param num
* #return
*/
private static String getLeadingZerosToNum(int num) {
// Initializing the string of zeros with required size
String zeros = new String("0000");
// Validating if num value is less then zero or if the length of number
// is greater then zeros configured to return the num value as is
if (num < 0 || String.valueOf(num).length() >= zeros.length()) {
return String.valueOf(num);
}
// Returning zeros in case if value is zero.
if (num == 0) {
return zeros;
}
return new StringBuilder(zeros.substring(0, zeros.length() -
String.valueOf(num).length())).append(
String.valueOf(num)).toString();
}
}
Input
0
7
13
713
7013
9999
Output
0000
0007
0013
7013
9999
No packages needed:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.

Categories

Resources