在 C++ 中存储精确到小数点后两位的浮点数

Store float with exactly 2 decimal places in C++

我想取一个十进制或非十进制值,并在 C++ 中将其存储为恰好有 2 位小数的字符串。我想这样做是为了将其显示为货币价值,因此它始终为 10.50 美元或 10.00 美元,而不是 10.5 美元或 10 美元。

我不只是想打印这个,我想存储它,所以我不相信 setprecision 会在这里工作。我在 Qt 应用程序中执行此操作,因此如果有使用 Qt 的方法,我也可以使用它。

例如:

int cents = 1000;
std::string dollars; //should get value from cents formatted to 10.00

更新: 看来我还没有词汇量,因为我刚刚开始学习 C++ 来表达我想做的事情。这是我想使用 Python:

做的事情
str_money = '$ {:.2f}'.format(num)

在此示例中,num 可以是小数或不是小数(例如 10 或 10.5)并且 str_money 是一个变量,它被赋予 num 的值作为小数,小数点后正好有 2 个数字(在此示例中,str_money 将变为 10.00 或 10.50)。我希望它将它存储在一个字符串变量中,我不需要它来存储带有值的“$”。

我可以在 C++ 中执行此操作吗?

如果你希望在输出上发生这种情况,那么 您可以使用 setprecision () 方法,因为它设置用于在 输出操作上格式化浮点值的小数精度。

找到更多 https://www.cplusplus.com/reference/iomanip/setprecision/#:~:text=std%3A%3Asetprecision&text=Sets%20the%20decimal%20precision%20to,input%20streams%20or%20output%20streams).

并检查此解决方案是否存在问题

https://www.geeksforgeeks.org/rounding-floating-point-number-two-decimal-places-c-c/

如果你想存储固定的小数位数,float不是你想要的。你想要 fixed-point number。对于货币,基本思想是将值存储为整数中的“美分”。然后,只要您想将值输出为“美元”,就可以执行除以 100 的操作。 (或者使用自定义输出函数或运算符来正确格式化输出。)

定点运算的一大好处是可以避免舍入误差。 Floating point 数字在精确存储小数方面确实很糟糕,因此处理“十分之一”或“百分之一”很容易导致舍入误差,这些误差会在长 运行 或复杂的程序中累加。

如何实现定点数在很大程度上取决于您。您可能会找到一个具有定点 class 的库,您可以实现自己的库,或者您可以只操作整数变量。

您决定将货币金额存储为美分整数是明智的,因为浮点数据类型(例如 floatdouble)通常是 deemed unsuitable for dealing with money

此外,您找到 std::setprecision 就差不多到了。但是,它需要与 std::fixed 结合使用才能达到预期效果(因为 std::setprecision 表示 different things 取决于使用的格式选项: default, 科学固定).

最后,要将格式化结果存储在 std::string 中而不是直接将其打印到控制台,您可以使用基于字符串的输出流 std::ostringstream。这是一个例子:

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

std::string cents_to_dollars_string(const int cents)
{
    static constexpr double cents_per_dollar{ 100. };
    static constexpr int decimal_places{ 2 };

    std::ostringstream oss;
    oss << std::fixed << std::setprecision(decimal_places) << cents / cents_per_dollar;
    return oss.str();
}

int main()
{
    const int balance_in_cents{ -420 };
    const std::string balance_in_dollars{ cents_to_dollars_string(balance_in_cents) };
    std::cout << "Your balance is " << balance_in_dollars << '\n';
}

在这里,我们首先定义函数 cents_to_dollars_string,它将以美分为单位的金额作为 int 和 returns 包含格式化美元金额的 std::string。然后,在 main 中,我们调用此函数将存储在 int 变量 balance_in_cents 中的金额(以美分为单位)转换为字符串,并将其存储到 std::string 变量中 balance_in_dollars。最后,我们将 balance_in_dollars 变量打印到控制台。