我有一个数字100000.我需要显示1,00,000。如何在没有的情况下使用Java中的字符串操作函数实现。提前谢谢。
答案 0 :(得分:1)
使用Java中提供的NumberFormat
实现或DecimalFormat
类。
e.g。
DecimalFormat dFormat = new DecimalFormat("#,##,####");
String value = dFormat.format(100000);
System.out.println("Formatted Value="+value);
答案 1 :(得分:0)
快速谷歌,我从here得到了这个。
此功能未内置于JavaScript中,因此需要使用自定义代码。以下是向数字添加逗号并返回字符串的一种方法。
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
答案 2 :(得分:0)
最简单的方法是:
function addCommas(num) {return (""+num).replace(/\B(?=(?:\d{3})+(?!\d))/g,',');}
有关更完整版本(包括对任意精度的十进制数的支持),请参阅numbar_format
on PHPJS
答案 3 :(得分:0)
这是Java中的解决方案,如果您仍然感兴趣,它只使用字符串方法来查找长度和字符位置。
int counter = 0;
int number=123456789;
String str = Integer.toString(number);
String finalStr = new String();
for(int i = str.length()-1; i >= 0; i--){
counter++;
if(counter % 3 == 0 && i != 0){
finalStr = ","+str.charAt(i)+finalStr;
}
else{
finalStr = str.charAt(i)+finalStr;
}
}
System.out.println("Final String: "+finalStr);
它使用值的长度循环并从右到左构建新字符串。每隔三个值(最后一个除外),它将在字符串前添加逗号。否则,它将继续并在逗号之间的临时值中构建字符串。
所以这会打印到控制台:
最终字符串:123,456,789