Estou entrando em um int
com um valor de 6 dígitos. Eu quero exibi-lo como uma String
com um ponto decimal (.) Em 2 dígitos do final do int
. Eu queria usar um float
mas foi sugerido para usar String
para uma melhor saída de exibição (em vez de 1234.5
será 1234.50
). Portanto, eu preciso de uma function que terá um int
como parâmetro e retornar a String
corretamente formatada com um ponto decimal 2 dígitos do final.
Dizer:
int j= 123456 Integer.toString(j); //processing... //output : 1234.56
int j = 123456; String x = Integer.toString(j); x = x.substring(0, 4) + "." + x.substring(4, x.length());
Como mencionado nos comentários, um StringBuilder é provavelmente uma implementação mais rápida usando um StringBuffer . Conforme mencionado nos documentos Java:
Essa class fornece uma API compatível com StringBuffer, mas sem garantia de synchronization. Esta class é projetada para uso como um substituto drop-in para StringBuffer em locais onde o buffer de seqüência de caracteres estava sendo usado por um único thread (como é geralmente o caso). Sempre que possível, recomenda-se que essa class seja usada em preferência a StringBuffer, pois ela será mais rápida na maioria das implementações.
Uso:
String str = Integer.toString(j); str = new StringBuilder(str).insert(str.length()-2, ".").toString();
Ou se você precisar de synchronization, use o StringBuffer com uso similar:
String str = Integer.toString(j); str = new StringBuffer(str).insert(str.length()-2, ".").toString();
int yourInteger = 123450; String s = String.format("%6.2f", yourInteger / 100.0); System.out.println(s);
Na maioria dos casos de uso, usar um StringBuilder
(como já foi respondido) é uma boa maneira de fazer isso. No entanto, se o desempenho é importante, isso pode ser uma boa alternativa.
/** * Insert the 'insert' String at the index 'position' into the 'target' String. * * ```` * insertAt("AC", 0, "") -> "AC" * insertAt("AC", 1, "xxx") -> "AxxxC" * insertAt("AB", 2, "C") -> "ABC * ```` */ public static String insertAt(final String target, final int position, final String insert) { final int targetLen = target.length(); if (position < 0 || position > targetLen) { throw new IllegalArgumentException("position=" + position); } if (insert.isEmpty()) { return target; } if (position == 0) { return insert.concat(target); } else if (position == targetLen) { return target.concat(insert); } final int insertLen = insert.length(); final char[] buffer = new char[targetLen + insertLen]; target.getChars(0, position, buffer, 0); insert.getChars(0, insertLen, buffer, position); target.getChars(position, targetLen, buffer, position + insertLen); return new String(buffer); }
Você poderia usar
System.out.printf("%4.2f%n", ((float)12345)/100));
De acordo com os comentários, 12345 / 100,0 seria melhor, assim como o uso de duplo em vez de flutuar.
Se você estiver usando um sistema onde float é caro (por exemplo, sem FPU) ou não permitido (por exemplo, em contabilidade), você poderia usar algo como isto:
for (int i = 1; i < 100000; i *= 2) { String s = "00" + i; System.out.println(s.substring(Math.min(2, s.length() - 2), s.length() - 2) + "." + s.substring(s.length() - 2)); }
Caso contrário, o DecimalFormat é a melhor solução. (a variante StringBuilder acima não funciona com números pequenos (<100)
public static void main(String[] args) { char ch='m'; String str="Hello",k=String.valueOf(ch),b,c; System.out.println(str); int index=3; b=str.substring(0,index-1 ); c=str.substring(index-1,str.length()); str=b+k+c; }
Eu acho que uma solução mais simples e mais elegante para inserir uma String em uma determinada posição seria este one-liner:
target.replaceAll("^(.{" + position + "})", "$1" + insert);
Por exemplo, para inserir uma falta :
em uma string de tempo:
"-0300".replaceAll("^(.{3})", "$1:");
O que ele faz é corresponder caracteres de position
do início da string, agrupá-lo e substituí-lo por si ( $1
) seguido pela string de insert
. Ocupe-se do replaceAll, mesmo que haja sempre uma ocorrência, porque o primeiro parâmetro deve ser um regex.
É claro que não tem o mesmo desempenho da solução StringBuilder, mas acredito que a sucessão e a elegância como uma simples e mais fácil de ler uma linha (em comparação com um método enorme) é suficiente para torná-la a solução preferida na maioria das performances casos de uso crítico.
Note que estou resolvendo o problema genérico no título por razões de documentação, é claro que se você está lidando com números decimais você deve usar as soluções específicas de domínio já propostas.
// Create given String and make with size 30 String str = "Hello How Are You"; // Creating StringBuffer Object for right padding StringBuffer stringBufferRightPad = new StringBuffer(str); while (stringBufferRightPad.length() < 30) { stringBufferRightPad.insert(stringBufferRightPad.length(), "*"); } System.out.println("after Left padding : " + stringBufferRightPad); System.out.println("after Left padding : " + stringBufferRightPad.toString()); // Creating StringBuffer Object for right padding StringBuffer stringBufferLeftPad = new StringBuffer(str); while (stringBufferLeftPad.length() < 30) { stringBufferLeftPad.insert(0, "*"); } System.out.println("after Left padding : " + stringBufferLeftPad); System.out.println("after Left padding : " + stringBufferLeftPad.toString());
Cordas welcomemsg = “0E020E2D0E1A0E040E380E130E170E350E480E2A0E210E310E040E230020004E0075006D00630068006F006B002000300031002800350E1A002F0E020E490E2D0E040E270E320E21002900200E2A0E2D0E1A0E160E320E21002000300032003200360031003200360037003800200E220E010E400E250E340E010E010E14002A00310033003700200E420E170E230E2D0E2D0E01”; System.out.println (“length welcomemsg =” + Math.ceil (welcomemsg.length () / 4));
int i = 4; int lengthwelcomemsg = welcomemsg.length()/i; String resultwelcomemsg = ""; for(int nadd=0;nadd