Jak sformatować liczbę ciągów, aby miała przecinki i okrągłe?

Jaki jest najlepszy sposób sformatowania następującej liczby, która jest mi dana jako ciąg znaków?

String number = "1000500000.574" //assume my value will always be a String

Chcę, aby to był łańcuch o wartości: 1,000,500,000.57

Jak to sformatować?

Author: Sheehan Alam, 2010-09-09

11 answers

Możesz spojrzeć na DecimalFormat class; obsługuje różne lokalizacje(np.: w niektórych krajach, które zamiast tego byłyby sformatowane jako 1.000.500.000,57).

Musisz również przekonwertować ten łańcuch na liczbę, można to zrobić za pomocą:

double amount = Double.parseDouble(number);

Próbka kodu:

String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");

System.out.println(formatter.format(amount));
 216
Author: NullUserException,
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
2015-11-17 20:21:08

Po przekonwertowaniu łańcucha znaków na liczbę, możesz użyć

// format the number for the default locale
NumberFormat.getInstance().format(num)

Lub

// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)
 32
Author: Aaron Novstrup,
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
2010-09-09 00:09:48

Można to również osiągnąć za pomocą ciągu znaków.format (), która może być łatwiejsza i / lub bardziej elastyczna, jeśli formatujesz wiele liczb w jednym łańcuchu.

    String number = "1000500000.574";
    Double numParsed = Double.parseDouble(number);

    System.out.println(String.format("The input number is: %,.2f", numParsed));
    // Or
    String numString = String.format("%,.2f", numParsed);

Dla ciągu formatu"%,.2f" -", "oznacza oddzielne grupy cyfr z przecinkami, oraz".2 " oznacza zaokrąglenie do dwóch miejsc po przecinku.

Aby zapoznać się z innymi opcjami formatowania, zobacz https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

 28
Author: Greg H,
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-06-05 17:11:59

Stworzyłem własne narzędzie do formatowania. Co jest niezwykle szybkie w przetwarzaniu formatowania wraz z dając wiele funkcji:)

Obsługuje:

  • formatowanie przecinkami np. 1234567 staje się 1,234,567.
  • przedrostek "tysiąc(K),milion(m),miliard(B),bilion(T)".
  • Dokładność od 0 do 15.
  • precyzyjna zmiana rozmiaru (oznacza, że jeśli chcesz 6-cyfrową precyzję, ale masz tylko 3 dostępne cyfry, wymusza to na 3).
  • obniżenie przedrostka (oznacza jeśli wybrany prefiks jest zbyt duży, obniża go do bardziej odpowiedniego prefiksu).

Kod można znaleźć tutaj . Nazywacie to tak:

public static void main(String[])
{
   int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
   String formatted = ValueFormat.format(1234567, settings);
}

Powinienem również zwrócić uwagę, że nie obsługuje obsługi dziesiętnej, ale jest bardzo przydatny dla wartości całkowitych. Powyższy przykład pokazuje" 1.23 M " jako wyjście. Mógłbym prawdopodobnie dodać wsparcie dziesiętne może, ale nie widziałem zbyt wiele wykorzystania dla niego od tego czasu mogę równie dobrze połączyć to w BigInteger typu klasy, która obsługuje skompresowane tablice char [] do obliczeń matematycznych.

 10
Author: Jeremy Trifilo,
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
2012-12-09 07:25:33
public void convert(int s)
{
    System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}

public static void main(String args[])
{
    LocalEx n=new LocalEx();
    n.convert(10000);
}
 6
Author: user3314142,
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-07-29 17:09:54

Możesz również użyć poniższego rozwiązania -

public static String getRoundOffValue(double value){

        DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
        return df.format(value);
}
 5
Author: Jitendra Nath,
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
2015-10-25 05:36:51

Możesz wykonać całą konwersję w jednej linii, używając następującego kodu:

String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));

Dwa ostatnie znaki # w Konstruktorze DecimalFormat również mogą być 0s. tak czy inaczej działa.

 3
Author: Peter Griffin,
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
2016-02-27 07:47:37

Oto najprostszy sposób, aby się tam dostać:

String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result)); 

Wyjście: 10,987,655.88

 3
Author: John Paker,
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-05-07 07:18:25

Pierwsza odpowiedź działa bardzo dobrze, ale dla zera / 0 sformatuje się jako .00

Stąd format #, # # 0.00 działa dobrze dla mnie. Zawsze testuj różne liczby, takie jak 0 / 100 / 2334.30 i liczby ujemne przed wdrożeniem do systemu produkcyjnego.

 2
Author: Venod Raveendran,
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-02-26 22:39:48

Biorąc pod uwagę, że jest to wynik Numer jeden w Google dla format number commas java, oto odpowiedź, która działa dla ludzi, którzy pracują z liczbami całkowitymi i nie dbają o liczby dziesiętne.

String.format("%,d", 2000000)

Wyjścia:

2,000,000
 0
Author: Ben Watson,
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-21 15:23:37

Ta klasa jest dla prostego Indyjskiego formatera Cen

public class Test {

public static void main (String a[]){
    System.out.println(priceFormatter("10023"));    
}
/**
 * This method is to convert the price into Indian price
 * separator format
 * @param inputPrice
 * @return
 */
public static String priceFormatter(String inputPrice){
    try {
        if(!isNumeric(inputPrice)){
            return inputPrice;
        }
        // to check if the number is a decimal number
        String newPrice = "",afterDecimal = "";
        if(inputPrice.indexOf('.') != -1){
            newPrice = inputPrice.substring(0,inputPrice.lastIndexOf('.'));
            afterDecimal = inputPrice.substring(inputPrice.lastIndexOf('.'));
        }else{
            newPrice = inputPrice;
        }
        int length = newPrice.length();
        if (length < 4) {
            return inputPrice;
        }
        // to check whether the length of the number is even or odd
        boolean isEven = false;
        if (length % 2 == 0) {
            isEven = true;
        }
        // to calculate the comma index
        char ch[] = new char[length + (length / 2 - 1)];
        if (isEven) {
            for (int i = 0, j = 0; i < length; i++) {
                ch[j++] = inputPrice.charAt(i);
                if (i % 2 == 0 && i < (length - 3)) {
                    ch[j++] = ',';
                }
            }
        } else {
            for (int i = 0, j = 0; i < length; i++) {
                ch[j++] = inputPrice.charAt(i);
                if (i % 2 == 1 && i < (length - 3)) {
                    ch[j++] = ',';
                }
            }
        }
        // conditional return based on decimal number check
        return afterDecimal.length() > 0 ? String.valueOf(ch) + afterDecimal : String.valueOf(ch);

    } catch(NumberFormatException ex){
        ex.printStackTrace();
        return inputPrice;
    }
      catch (Exception e) {
        e.printStackTrace();
        return inputPrice;
    }
}

}
 -2
Author: Nitin Jha,
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-08-20 08:51:57