¿Cómo dejaste el pad an int
con ceros al convertir a a String
en java?
Básicamente, estoy buscando rellenar enteros 9999
con ceros a la izquierda (por ejemplo, 1 = 0001
).
fuente
¿Cómo dejaste el pad an int
con ceros al convertir a a String
en java?
Básicamente, estoy buscando rellenar enteros 9999
con ceros a la izquierda (por ejemplo, 1 = 0001
).
Usar java.lang.String.format(String,Object...)
así:
String.format("%05d", yournumber);
para el relleno cero con una longitud de 5. Para la salida hexadecimal, reemplace el d
con un x
como en "%05x"
.
Las opciones de formato completo se documentan como parte de java.util.Formatter
.
String.format
sean similares a printf () en C?
%012d
%d can't format java.lang.String arguments
Digamos que quieres imprimir 11
como011
Se puede usar un formateador : "%03d"
.
Puede usar este formateador de esta manera:
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
Alternativamente, algunos métodos de Java admiten directamente estos formateadores:
System.out.printf("%03d", a);
F
de formato () debe ser f
: String.format(...);
.
int prefixLength = requiredTotalLength - String.valueOf(numericValue).length
. Ej. ) Y luego uso un método de cadena de repetición para crear el prefijo requerido. Hay varias formas de repetir cadenas, pero no hay una Java nativa, afaik: stackoverflow.com/questions/1235179/…
Si por alguna razón usa Java pre 1.5, puede intentar con el método Lang de Apache Commons
org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
Encontré este ejemplo ... Lo probaré ...
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));
}
}
Probado esto y:
String.format("%05d",number);
Ambos funcionan, para mis propósitos creo que String.Format es mejor y más sucinto.
Si el rendimiento es importante en su caso, puede hacerlo usted mismo con menos sobrecarga en comparación con la String.format
función:
/**
* @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();
}
Actuación
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");
}
Resultado
Función propia: 1697 ms
Formato de cadena: 38134 ms
for( int i : data ) strData += (i > 9 ? (i > 99 ? "" : "0") : "00") + Integer.toString( i ) + "|";
funcionó muy rápido (¡perdón, no lo cronometré!).
Puedes usar Google Guava :
Maven
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
Código de muestra:
String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
Nota:
Guava
es una biblioteca de gran utilidad, sino que también ofrece un montón de características que se referían a Collections
, Caches
, Functional idioms
, Concurrency
, Strings
, Primitives
, Ranges
, IO
, Hashing
, EventBus
, etc.
Ref: Guayaba Explicada
Prueba este:
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
Aunque muchos de los enfoques anteriores son buenos, a veces necesitamos formatear enteros y flotantes. Podemos usar esto, particularmente cuando necesitamos rellenar un número particular de ceros a la izquierda y a la derecha de los números decimales.
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);
si desea imprimir el texto formateado directamente en la pantalla.
String.format
y System.out.format
llamar a la misma java.util.Formatter
implementación.
Use la clase DecimalFormat, así:
NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811));
SALIDA: 0000811
Aquí es cómo puede formatear su cadena sin usar DecimalFormat
.
String.format("%02d", 9)
09
String.format("%03d", 19)
019
String.format("%04d", 119)
0119
Verifique mi código que funcionará para entero y String.
Supongamos que nuestro primer número es 2. Y queremos agregar ceros a eso para que la longitud de la cadena final sea 4. Para eso, puede usar el siguiente código
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);
(new char[diff])
por qué
replace("\0", "0")
qué es ... qué
Debe usar un formateador, el siguiente código usa 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));
Salida: 0001
public static String zeroPad(long number, int width) {
long wrapAt = (long)Math.pow(10, width);
return String.valueOf(number % wrapAt + wrapAt).substring(1);
}
El único problema con este enfoque es que te hace ponerte el sombrero de pensamiento para descubrir cómo funciona.
number
o width
mayor que 18.
No se necesitan paquetes:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
Esto rellenará la cadena con tres caracteres y es fácil agregar una parte más para cuatro o cinco. Sé que esta no es la solución perfecta de ninguna manera (especialmente si quieres una cadena acolchada grande), pero me gusta.
new String(Integer.toString(num + 10000)).substring(1)
enfoque sinum
es mayor que 9999, ijs.