繁体   English   中英

限制浮点精度?

[英]Limit floating point precision?

有没有办法将浮点四舍五入到 2 点? 例如: 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)); 
}

如果您要打印出来,请改用您可用的任何打印格式功能。

在 C++ 中

cout << setprecision(2) << f; 

要舍入以呈现到 GUI,请使用 std::ostringstream

对于那些像我一样使用谷歌搜索将浮点数格式化为货币的人:

#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"

您必须将其作为字符串返回。 将它放回浮点数会失去精度。

乘以 100,四舍五入为整数(无论如何你想要),除以 100。请注意,由于 1/100 不能用浮点精确表示,请考虑保留固定精度整数。

不要使用浮动。 如果要打印美元,请使用存储美分数的整数并在最后 2 位之前打印小数点。 浮点数对于金钱来说几乎总是错误的,除非你在做简单的计算(比如简单的经济数学模型),其中只有数字的大小才是真正重要的,而且你永远不会减去附近的数字。

尝试使用

std::cout<<std::setprecision(2)<<std::cout<<x;

应该可以工作,并且浮点数出现后只有 2 位数字。

我没有找到让我满意的干净答案,因为大多数干净的答案都假设您需要打印结果,如果您只是将一些数据存储到可接受的分辨率,则情况可能并非如此:

#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

您还可以为Tprecision添加静态检查(在编译时签名的情况下)。

要限制精度:
如果 x 是浮点数,则不舍入:
(上移2位小数,去掉小数,下移2位小数)

((int)(x*100.0)) / 100.0F

带四舍五入的浮动:

((int)(x*100.0 + 0.5F)) / 100.0F

双无四舍五入:

((long int)(x*100.0)) / 100.0

双带四舍五入:

((long int)(x*100.0 + 0.5)) / 100.0

注意:因为 x 要么是float要么是double ,所以小数部分将始终存在。 这是 # 的表示方式 ( IEEE 754 ) 和 # 的精度之间的区别。
C99 支持round()

试试这个,它完美地工作

float=3576.7675745342556;
printf("%.2f",float);

更改其中的一些对象以查看和学习代码。

yourFloatNumber= Float.Round(yourFloatNumber,2); // In C#

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM