我知道这是一个很老的帖子,但我今天消失在man
兔子洞里,所以我想我会记录下我的旅行:
strfmon()
您可以包含一个名为的函数monetary.h
来执行此操作,并根据本地或国际标准执行此操作。
请注意,它的工作方式类似于printf()
,并且将采用与字符串中指定的格式一样多double
的参数。%
它比我这里的要多得多,我发现这个页面是最有帮助的:https ://www.gnu.org/software/libc/manual/html_node/Formatting-Numbers.html
#include <monetary.h>
#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
// need to setlocal(), "" sets locale to the system locale
setlocale(LC_ALL, "");
double money_amt = 1234.5678;
int buf_len = 16;
char simple_local[buf_len];
char international[buf_len];
char parenthesis_for_neg[buf_len];
char specified_width[buf_len];
char fill_6_stars[buf_len];
char fill_9_stars[buf_len];
char suppress_thousands[buf_len];
strfmon(simple_local, buf_len-1, "%n", money_amt);
strfmon(international, buf_len-1, "%i", money_amt);
strfmon(parenthesis_for_neg, buf_len-1, "%(n", money_amt);
strfmon(specified_width, buf_len-1, "%#6n", money_amt);
strfmon(fill_6_stars, buf_len-1, "%=*#6n", money_amt);
strfmon(fill_9_stars, buf_len-1, "%=*#8n", money_amt);
strfmon(suppress_thousands, buf_len-1, "%^=*#8n", money_amt);
printf( "===================== Output ===================\n"\
"Simple, local: %s\n"\
"International: %s\n"\
"parenthesis for negatives: %s\n"\
"fixed width (6 digits): %s\n"\
"fill character '*': %s\n"\
"-- note fill characters don't\n"\
"-- count where the thousdands\n"\
"-- separator would go:\n"\
"filling with 9 characters: %s\n"\
"Suppress thousands separators: %s\n"\
"================================================\n",
simple_local, international, parenthesis_for_neg,
specified_width, fill_6_stars, fill_9_stars,
suppress_thousands);
/** free(money_string); */
return 0;
}
===================== Output ===================
Simple, local: $1,234.57
International: USD1,234.57
parenthesis for negatives: $1,234.57
fixed width (6 digits): $ 1,234.57
fill character '*': $**1,234.57
-- note fill characters don't
-- count where the thousdands
-- separator would go:
filling with 9 characters: $*****1,234.57
Suppress thousands separators: $****1234.57
================================================