왼쪽에 0이있는 정수를 어떻게 채울 수 있습니까?
Java int
에서 a String
로 변환 할 때 어떻게 0으로 패딩을 남겼 습니까?
기본적으로 9999
선행 0 (예 : 1 = 0001
) 까지 정수를 채우려 고합니다 .
다음 java.lang.String.format(String,Object...)
과 같이 사용하십시오 .
String.format("%05d", yournumber);
길이가 5 인 제로 패딩의 경우 16 진수 출력의 경우 d
를에서 x
as로 바꿉니다 "%05x"
.
전체 서식 옵션은의 일부로 설명되어 있습니다 java.util.Formatter
.
어떤 이유로 든 1.5 이전 Java를 사용하는 경우 Apache Commons Lang 방법을 사용해 볼 수 있습니다.
org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
다음 11
과 같이 인쇄하고 싶다고 가정 해 보겠습니다.011
포맷터를 사용할 수 있습니다 : "%03d"
.
이 포맷터를 다음과 같이 사용할 수 있습니다.
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
또는 일부 Java 메소드는 다음 포맷터를 직접 지원합니다.
System.out.printf("%03d", a);
이 예를 찾았습니다 ... 테스트하겠습니다 ...
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));
}
}
이것을 테스트하고 :
String.format("%05d",number);
두 가지 모두 내 목적을 위해 String.Format이 더 좋고 간결하다고 생각합니다.
귀하의 경우 성능이 중요하다면 String.format
함수에 비해 적은 오버 헤드로 직접 수행 할 수 있습니다.
/**
* @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();
}
공연
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");
}
결과
자신의 기능 : 1697ms
String.format : 38134ms
Google Guava 를 사용할 수 있습니다 .
메이븐 :
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
샘플 코드 :
String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
노트 :
Guava
매우 유용한 라이브러리, 그것은 또한 관련 기능을 많이 제공 Collections
, Caches
, Functional idioms
, Concurrency
, Strings
, Primitives
, Ranges
, IO
, Hashing
, EventBus
, 등
참조 : 구아바
이걸로 해봐:
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // 0009
String a = df.format(99); // 0099
String b = df.format(999); // 0999
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.
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
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);
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
public static String zeroPad(long number, int width) {
long wrapAt = (long)Math.pow(10, width);
return String.valueOf(number % wrapAt + wrapAt).substring(1);
}
The only problem with this approach is that it makes you put on your thinking hat to figure out how it works.
No packages needed:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
이렇게하면 문자열이 3 자로 채워지며 4 ~ 5 개의 부분을 추가하기 쉽습니다. 나는 이것이 어떤 식 으로든 완벽한 해결책이 아니라는 것을 알고 있지만 (특히 큰 패딩 문자열을 원한다면) 좋아합니다.
참고 URL : https://stackoverflow.com/questions/473282/how-can-i-pad-an-integer-with-zeros-on-the-left
'programing tip' 카테고리의 다른 글
동시성과 병렬성의 차이점은 무엇입니까? (0) | 2020.09.28 |
---|---|
인라인 CSS에서 a : hover를 작성하는 방법은 무엇입니까? (0) | 2020.09.28 |
Java에서 현재 스택 추적 가져 오기 (0) | 2020.09.28 |
여러 열에서 그룹화 사용 (0) | 2020.09.28 |
유효한 정규식을 감지하는 정규식이 있습니까? (0) | 2020.09.28 |