如何正确格式化c++浮点数到小数点后两位
visual How do I properly format C++ floats to two decimal places?
我使用setprecision有一些问题。我完全不明白它是怎么工作的。我搜索了这个问题,并能够推断出一些应该工作的代码。我不明白为什么不是。谢谢你的帮助,我在这方面还是个新手。
//monthly paycheck.cpp
//Paycheck Calculator
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
//Constants
const double
FEDERAL_TAX = 0.15, //Federal Tax
STATE_TAX = 0.035, //State Tax
SSA_TAX = 0.085, //Social Security & Medicare
HEALTH_INSURANCE = 75; //Health Insurance
//Variables
int year;
double grossAmount;
string employeeName, month;
// Initialize variables with input
cout << "Hello, what's your first name? ";
cin >> employeeName;
cout << "What is your gross amount? ";
cin >> grossAmount;
cout << "Please enter the month and year: ";
cin >> month >> year;
// Output
cout << "***********************************" << endl;
cout << "Paycheck" << endl;
cout << "Month: " << month << "tYear: " << year << endl;
cout << "Employee Name: " << employeeName << endl;
cout << "***********************************" << endl;
cout << setprecision(5) << fixed;
cout << "Gross Amount: $" << grossAmount << endl;
cout << "Federal Tax: $" << FEDERAL_TAX*grossAmount << endl;
cout << "State Tax: $" << STATE_TAX*grossAmount << endl;
cout << "Social Sec / Medicare: $" << SSA_TAX*grossAmount << endl;
cout << "Health Insurance: $" << HEALTH_INSURANCE << endl << endl;
cout << "Net Amount: $" << fixed << grossAmount-grossAmount*(FEDERAL_TAX+STATE_TAX+SSA_TAX)-HEALTH_INSURANCE << endl << endl;
system("PAUSE");
return 0;
}
如果您想在c++流中格式化浮点数以2位小数显示,您可以轻松地:
float a = 5.1258f;
std::cout << std::fixed << std::setprecision(2) << a << std::endl;
参见std::fixed和std::setprecision
使用流操纵符:
std::cout.fixed;
std::cout.precision(Number_of_digits_after_the_decimal_point);
相关文章:
- 如何在 c++ 中将小数点后两位数的浮点数分配给另一个浮点数
- 如何在C ++中替换整数的前两位数字?
- 如何输出计算到小数点后两位的中间器?
- 将两位数字转换为低内存表示的最快方法
- 如何在 C/C++ 中有效地计算双倍到两个小数点精度
- 如何在计算器中将大数字表示为小数点后两位C++
- 可视化 如何使用C++向右强制小数点后两位
- 四舍五入双小数点后两位
- 将浮点数限制为小数点后两位
- C++ 如何获取兰登数以及如何保存带有 ONY 两位小数的双精度
- 使用 "double" 输出具有两位小数的值
- 程序查找并打印第一个完全正方形 (i*i),其最后两位数字都是奇数
- 转换为十六进制并删除最后两位数字
- 我将如何在不使用 if 语句、字符数组、apstring 或 atoi 的情况下将带有两位数字的字符串转换为 int
- C++四舍五入小数点后两位
- 如何正确格式化c++浮点数到小数点后两位
- 四舍五入浮点数:精确地输出小数点后的两位数字
- 我在试着编写一种疾病在不同年龄段的发病率,我需要把它写成一个百分数它的精度是小数点后两位
- 如何将双精度转换为小数点后两位
- 将字节转换为两位十六进制数字