我很难将小数值对齐。我相信这是右对齐和setprecision / fixed的组合,但似乎并没有起作用。我知道其他问题已经问过了,但我还没有找到一个清晰的解决方案来使一堆列(唯一的cout语句对齐)。这是我的代码块:
这是它的原貌:
这就是我期望它呈现的效果:
double total_collect, sales, country_tax, state_tax, total_tax;
const double STATE_TAX_RATE = 0.04, COUNTRY_TAX_RATE = 0.02;
// Compute taxes
total_collect = 100;
sales = 100 / 1.06 ;
country_tax = sales * COUNTRY_TAX_RATE;
state_tax = sales * STATE_TAX_RATE;
total_tax = country_tax + state_tax;
//Display
cout << setiosflags(std::ios::right) ;
cout << "Totla Collected: " << setw(7) << "$ " << fixed << setprecision(2) << right << total_collect << endl;
cout << "Sales: " << setw(17) << "$ " << fixed << setprecision(2) << right << sales << endl;
cout << "Country Sales Tax: " << setw(5) << "$ " << fixed << setprecision(2) << right << country_tax << endl;
cout << "State Sales Tax: " << setw(7) << "$ " << fixed << setprecision(2) << right << state_tax << endl;
cout << "Total Sales Tax: " << setw(7) << "$ " << fixed << setprecision(2) << left << total_tax << endl << endl;
这是它的原貌:
这就是我期望它呈现的效果:
std::stringstream
。 - Fred Larsonint(val)
和int(round(val*x))%x
来找到小数点左右的组成部分,其中上面的例子中 x 为 100。(负值需要稍微多做一些工作,并且 LHS 和小数点本身的格式仍应通过区域设置完成。)在我看来,这不太优雅,但它能够产生与货币格式化相同的输出,而不限于可以在区域设置的货币中表示的值。 - John P