簡體   English   中英

分數千java

[英]Split number thousand java

我想通過在其中添加一些逗號來拆分一些String 例如 :

"1234" => "1,234"
"12345" => "12,345"
"123456" => "123,456"
"1234567" => "1,234,567"
"12345678" => "12,345,678"
"123456789" => "123,456,789"

我可以擁有像“123456789123456789123456789123456789123456789”這樣龐大的字符串

目前,我使用這個代碼與DecimalFormat但因為我轉換為double,我的數字限制為Double的范圍,所以我需要找到另一種方法來避免這個范圍。 我收到一個String ,我想解析它像一個字符串,而不是一個數字( IntegerDouble )。 我想我可以使用正則表達式或類似的東西,但我不知道該怎么做。

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
DecimalFormat df = new DecimalFormat("###,###", symbols);
formattedStr = df.format(Double.parseDouble(str));

要么使用其他答案中提到的BigInteger ,要么使用正則表達式,如下所示:

public class Test {
     public static void main(String[] args) {
         String s = "12345678912345678912345678";
         String formatted = s.replaceAll("(\\d)(?=(\\d{3})+$)", "$1,");
         System.out.println(formatted); // 12,345,678,912,345,678,912,345,678
     }
}

表達式將在所有數字后面附加一個逗號,后跟至少一組3位數字。

要擁有如此龐大的數字,您必須使用BigIntegerBigDecimal 這段代碼應該可以幫到你:

public static void main(String[] args) {
    BigInteger integer = BigInteger.valueOf(60000);

    String result = NumberFormat.getNumberInstance(Locale.US).format(
        integer);
    System.out.println(result);
}

產量:60,000

祝好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM