Wstaw Znak w łańcuchu w określonej pozycji

Wchodzę w int z 6-cyfrową wartością. Chcę wyświetlić go jako String z przecinkiem (.) na 2 cyfry od końca int. Chciałem użyć float, ale zasugerowano użycie String dla lepszego wyświetlania (zamiast 1234.5 będzie 1234.50). Dlatego potrzebuję funkcji, która przyjmie int jako parametr i zwróci poprawnie sformatowane {[2] } z przecinkiem 2 cyfry od końca.

Powiedz:

int j= 123456 
Integer.toString(j); 

//processing...

//output : 1234.56
Author: Bilesh Ganguly, 2011-05-04

10 answers

int j = 123456;
String x = Integer.toString(j);
x = x.substring(0, 4) + "." + x.substring(4, x.length());
 153
Author: Mike Thomsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-04 13:45:11

Jak wspomniano w komentarzach, StringBuilder jest prawdopodobnie szybszą implementacją niż użycie StringBuffer . Jak wspomniano w dokumentach Java:

Ta klasa dostarcza API kompatybilne z StringBuffer, ale bez gwarancji synchronizacji. Klasa ta jest przeznaczona do użycia jako zamiennik StringBuffer w miejscach, w których bufor łańcuchów był używany przez pojedynczy wątek (jak to zwykle bywa). W miarę możliwości zaleca się klasa będzie używana zamiast StringBuffer, ponieważ będzie szybsza w większości implementacji.

Użycie:

String str = Integer.toString(j);
str = new StringBuilder(str).insert(str.length()-2, ".").toString();

Lub jeśli potrzebujesz synchronizacji użyj StringBuffer z podobnym użyciem:

String str = Integer.toString(j);
str = new StringBuffer(str).insert(str.length()-2, ".").toString();
 178
Author: blo0p3r,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-25 11:48:32
int yourInteger = 123450;
String s = String.format("%6.2f", yourInteger / 100.0);
System.out.println(s);
 15
Author: Itay Maman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-03 13:02:02

W większości przypadków użycie StringBuilder (Jak już odpowiedzieliśmy) jest dobrym sposobem na to. Jednak jeśli wydajność ma znaczenie, może to być dobra alternatywa.

/**
 * 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);
}
 4
Author: rmuller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-03 10:04:21

You could use

System.out.printf("%4.2f%n", ((float)12345)/100));

Zgodnie z komentarzami, 12345/100.0 byłoby lepsze, podobnie jak użycie double zamiast float.

 3
Author: Joseph Ottinger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-05 13:46:52

Jeśli używasz systemu, w którym float jest drogi (np. brak FPU) lub niedozwolony (np. w księgowości), możesz użyć czegoś takiego:

    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));
    }

W Przeciwnym Razie format dziesiętny jest lepszym rozwiązaniem. (powyższy wariant StringBuilder nie będzie działał z małymi liczbami (

 0
Author: rurouni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-04 13:59:00
  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;
}
 0
Author: Miya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-16 03:10:34

Myślę, że prostszym i bardziej eleganckim rozwiązaniem, aby wstawić ciąg w określonej pozycji, byłoby to jednoliniowe: {]}

target.replaceAll("^(.{" + position + "})", "$1" + insert);

Na przykład, aby wstawić brakujące : Do ciągu czasu:

"-0300".replaceAll("^(.{3})", "$1:");

To, co robi, to dopasowuje position znaki z początku łańcucha, grupuje i zastępuje grupę samą sobą ($1), po którym następuje łańcuch insert. Zwróć uwagę na zamiennik, mimo że zawsze występuje jedno wystąpienie, ponieważ pierwszy parametr musi być wyrażeniem regularnym.

Z oczywiście nie ma takiej samej wydajności jak rozwiązanie StringBuilder, ale uważam, że zwięzłość i elegancja jako prosty i łatwiejszy do odczytania jednowarstwowy (w porównaniu do ogromnej metody) jest wystarczająca, aby uczynić go preferowanym rozwiązaniem w większości przypadków nie krytycznych pod względem wydajności.

Uwaga rozwiązuję Ogólny problem w tytule ze względów dokumentacyjnych, oczywiście jeśli masz do czynienia z liczbami dziesiętnymi, powinieneś skorzystać z proponowanych rozwiązań specyficznych dla danej domeny.

 0
Author: Luan Nico,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-13 13:04:12
// 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());
 0
Author: Nagendra Mishra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-20 14:01:52

Spróbuj tego:

public String ConvertMessage(String content_sendout){

        //use unicode (004E00650077) need to change to hex (&#x004E&#x;0065&#x;0077;) first ;
        String resultcontent_sendout = "";
        int i = 4;
        int lengthwelcomemsg = content_sendout.length()/i;
        for(int nadd=0;nadd<lengthwelcomemsg;nadd++){
            if(nadd == 0){
                resultcontent_sendout = "&#x"+content_sendout.substring(nadd*i, (nadd*i)+i) + ";&#x";
            }else if(nadd == lengthwelcomemsg-1){
                resultcontent_sendout += content_sendout.substring(nadd*i, (nadd*i)+i) + ";";
            }else{
                resultcontent_sendout += content_sendout.substring(nadd*i, (nadd*i)+i) + ";&#x";
            }
        }
        return resultcontent_sendout;
    }
 0
Author: Pattanai Pornpibul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-07 11:19:54