输出逗号分隔 [英] Comma separation in output
问题描述
如何可以在像1000,10000,100000,1000000一个输入给定一个号码的数字之间得到逗号和它的一些类似物的位数分离
1000
万
100000
1,000,000输出
How can I get comma in between the digits of a number given in a input like 1000,10000,100000,1000000 and it separates the digits of a number like 1,000 10,000 100,000 1,000,000 as an output
时的任何功能(库)使用C做一个计划吗?
Is any function(library) in C to make a program for this ?
推荐答案
使用非标准
印刷标志和设置语言环境:
Using the non standard '
print flag and setting locales:
#include <locale.h>
#include <stdio.h>
int main()
{
int value = 1234567;
if (!setlocale(LC_ALL, "en_US.UTF-8")) {
fprintf(stderr, "Locale not found.\n");
return 1;
}
printf("%'d\n", value);
return 0;
}
但是,使用 X模3 的和达夫设备你可以建立自己的(便携式)功能:
But using x mod 3 and a Duff's device you can build your own (portable) function:
#include <stdio.h>
#include <stdlib.h>
char *thousand_sep(long x)
{
char s[64], *p = s, *q, *r;
int len;
len = sprintf(p, "%ld", x);
q = r = malloc(len + (len / 3) + 1);
if (r == NULL) return NULL;
if (*p == '-') {
*q++ = *p++;
len--;
}
switch (len % 3) {
do {
*q++ = ',';
case 0: *q++ = *p++;
case 2: *q++ = *p++;
case 1: *q++ = *p++;
} while (*p);
}
*q = '\0';
return r;
}
int main(void)
{
char *s = thousand_sep(1234567);
printf("%s\n", s);
free(s);
return 0;
}
输出:
1,234,567
编辑:
如果我希望做同样在Java中,然后??
if i wish to make the same in java then??
对不起,我不(使用正则表达式的JavaScript中)叩头的Java,也许有用:
Sorry, I don't kow Java, maybe useful (in javascript using regex's):
Number.prototype.thousand_sep = function(decs){
var n = this.toFixed(decs).toString().split('.');
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return n.join('.');
};
...
var x = 1234567;
alert(x.thousand_sep(0));
这篇关于输出逗号分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!