gpt4 book ai didi

java - 在字符串中放入逗号

转载 作者:行者123 更新时间:2023-12-02 08:48:25 24 4
gpt4 key购买 nike

今天,我遇到了逗号问题。我想将逗号放入字符串中,如下所示:

String before = "12345678901234";
String after = commaInString(before); //This is the function that I want to make, but with no luck yet.
System.out.println(after); // This should show 12,345,678,901,234

所以,我现在要做的是制作 commaInString(String string) 函数,并且我在下面制作了一个测试函数:

public static String commaInString(String string) {
int stringSize = string.length();
int fsize = stringSize % 3;
StringBuffer sb = new StringBuffer();
int j = 0;
for(int k=0;k<stringSize;k++) {
if(fsize !=0 && k<fsize) j=0;
else if(fsize !=0 && k==fsize) sb.append(",");
j++;
sb.append(string.substring(k,k+1));
if(j%3==0 && (j+fsize)!=stringSize) sb.append(",");
}

string=sb.toString();
return string;
}

但是,它只适用于某些数字,我不知道为什么。我无法使用 DecimalFormat,因为数字太大而无法成为整数。我想在“字符串”本身中添加逗号。我可以对上面的函数做出什么安排来解决这个问题?请帮忙。

最佳答案

一种简单的方法是使用 BigInteger 和任何现有的格式化程序,例如

BigInteger num = new BigInteger("12345678901234567890");
String formatted = String.format("%,d", num);
// 12,345,678,901,234,567,890

关于java - 在字符串中放入逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60934555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com