曾经有过这个小功能
string format_dollars_for_screen(float d)
{
char ch[50];
sprintf(ch,"%1.2f",d);
return ch;
}
喜欢退货的人-0.00
。
我把它修改为
string format_dollars_for_screen(float d)
{
char ch[50];
float value;
sprintf(ch,"%1.2f",d);
value = stof(ch);
if(value==0.0f) sprintf(ch,"0.00");
return ch;
}
它开始根据需要返回0.00
。我的问题是,为什么这个其他解决方案不起作用?
string format_dollars_for_screen(float d)
{
char ch[50];
float value;
sprintf(ch,"%1.2f",d);
value = stof(ch);
if(value==0.0f) sprintf(ch,"%1.2f", value);
return ch;
}
和/或有没有更有效的方法来做到这一点?这只是我的想法,所以欢迎批评。=)
浮点数既有加零又有减零。它们与==
运算符相比是相等的,但在其他算术表达式中会产生不同的结果:1/0==inf
。
就你的情况而言,你不应该使用浮点数来表示货币数量。相反,使用整数来计算美分(或美分的其他小数部分),并相应地格式化它们:
string format_dollars_for_screen(int cents)
{
bool neg = cents < 0;
if(neg) cents = -cents;
char ch[50];
sprintf(ch, "%s%d.%.2d", "-"+!neg, cents/100, cents%100);
return ch;
}