C语言如何让价格显示小数点后两位?格式化输出问题求助
C语言价格格式化输出:显示1-2位小数的解决方案
你当前用%-20lf输出价格时,默认会显示6位小数(如20.000000),要实现仅显示1-2位小数的需求,可参考以下两种方案:
方案一:动态判断小数部分,强制显示1-2位
如果要求整数价格显示为20.0,带小数的价格显示为20.50或20.55,可通过判断价格是否为整数来选择格式符:
void displayItems(){ system("cls"); printf("Display Items!\n\n"); printf("%-10s %-20s %-20s %-20s %s\n", "ID", "Name Item", "Price", "Quantity", "Date"); printf ("---------------------------------------------------------------------------------------------\n"); fp = fopen("items.txt", "rb"); while(fread(&p, sizeof(p), 1, fp)== 1){ // 判断价格小数部分是否为0 if (p.price == (int)p.price) { printf("%-10d %-20s %-20.1lf %-20d %s\n", p.id, p.namaItem, p.price, p.quantity, p.date); } else { printf("%-10d %-20s %-20.2lf %-20d %s\n", p.id, p.namaItem, p.price, p.quantity, p.date); } } fclose(fp); }
方案二:使用%g自动精简小数位
如果接受整数价格显示为20(而非20.0),带小数的价格自动去掉末尾无效0(如20.50显示为20.5),可直接用%-20.2g格式符:
void displayItems(){ system("cls"); printf("Display Items!\n\n"); printf("%-10s %-20s %-20s %-20s %s\n", "ID", "Name Item", "Price", "Quantity", "Date"); printf ("---------------------------------------------------------------------------------------------\n"); fp = fopen("items.txt", "rb"); while(fread(&p, sizeof(p), 1, fp)== 1){ printf("%-10d %-20s %-20.2g %-20d %s\n", p.id, p.namaItem, p.price, p.quantity, p.date); } fclose(fp); }
补充说明
你之前尝试的%0.2lf是补零填充+固定两位小数的格式,和你需要的左对齐+1-2位自适应不符,正确的固定两位小数左对齐格式是%-20.2lf,但它无法实现小数位的自适应调整。
内容的提问来源于stack exchange,提问作者Alexander
相关产品推荐
相关产品推荐

