有没有一种方法将浮点数四舍五入到小数点后两位?例如:3576.7675745342556
变成 3576.76
。
有没有一种方法将浮点数四舍五入到小数点后两位?例如:3576.7675745342556
变成 3576.76
。
round(x * 100) / 100.0
如果必须使用浮点数:roundf(x * 100) / 100.0
使用标准库函数的灵活版本:
double GetFloatPrecision(double value, double precision)
{
return (floor((value * pow(10, precision) + 0.5)) / pow(10, precision));
}
floor
而不是round
? - pooya13value * pow(10, precision) + 0.5
的方法存在以下问题:1)许多负数会失败;2)加法在中间情况下会产生不精确性;3)乘法会溢出。 - chux - Reinstate Monicacout << setprecision(2) << f;
对于要在GUI中进行四舍五入的情况,可以使用std::ostringstream。
floor
或ceil
代替整数转换。 - Ben Voigtprintf("%.2f", f);
。 - Svante将数值乘以100,四舍五入为整数(任何方式),再除以100。请注意,由于浮点数无法精确表示1/100,因此考虑使用定点整数。
如果你像我一样想将浮点数格式化为货币形式,请参考以下内容:
#include <iomanip>
#include <sstream>
#include <string>
std::string money_format (float val)
{
std::ostringstream oss;
oss << std::fixed << std::setfill ('0') << std::setprecision (2) << val;
return oss.str();
}
// 12.3456 --> "12.35"
// 1.2 --> "1.20"
你必须返回它作为一个字符串。将其转换回浮点数会损失精度。
不要使用浮点数。使用存储以美分为单位的整数,并在最后两位之前打印小数点,如果要打印美元。除非您进行简单的计算(如天真的经济数学模型),其中仅数字的大小真正重要且您从未减去附近的数字,否则浮点数几乎总是错误的。
尝试使用
std::cout<<std::setprecision(2)<<std::cout<<x;
应该可以正常工作,只显示浮点数后的两位数字。
试试这个,它完美地工作。
float=3576.7675745342556;
printf("%.2f",float);
更改其中的一些对象以查看和学习代码。
我没有找到一个令我满意的干净答案,因为大多数干净的答案都假定你需要打印结果,但如果你只是将一些数据存储到可接受的分辨率,这可能并不是必需的:
#include <sstream>
template<typename T>
T toPrecision(T input, unsigned precision)
{
static std::stringstream ss;
T output;
ss << std::fixed;
ss.precision(precision);
ss << input;
ss >> output;
ss.clear();
return output;
}
template<unsigned P, typename T>
T toPrecision(T input) { return toPrecision(input, P); }
// compile-time version
double newValue = toPrecision<2>(5.9832346739); // newValue: 5.98
// run-time version
double newValue = toPrecision(3.1415, 2); // newValue: 3.14
T
和precision
(在编译时签名的情况下)添加静态检查。stringstream
设为 static
以减少成本,并删除了令人困惑的注释。干杯! - pooya13(int)(x*100.0)
的乘积超出int
范围时,会失败。即使使用intmax_t
也不足以解决问题。x*100.0 + 0.5F
的方法会像这样失败。 - chux - Reinstate Monica