我想取一個十進制或非十進制值并將其存盤為 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 中做到這一點嗎?
uj5u.com熱心網友回復:
您決定將貨幣金額存盤為整數美分是一個明智的決定,因為浮點資料型別(例如floator double)通常被認為不適合處理 money。
此外,您幾乎可以通過找到std::setprecision. 但是,它需要結合使用std::fixed才能產生預期的效果(因為根據使用的格式選項std::setprecision意味著不同的東西:默認、科學或固定)。
最后,要將格式化結果存盤在 an 中,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,它將以美分為單位的金額作為 anint并回傳std::string包含格式化的美元金額的an 。然后,main我們呼叫此函式將存盤在int變數中的金額(以美分為單位)轉換balance_in_cents為字串并將其存盤到std::string變數中balance_in_dollars。最后,我們將balance_in_dollars變數列印到控制臺。
uj5u.com熱心網友回復:
如果你想存盤固定的小數位數,afloat不是你想要的。你想要一個定點數。對于貨幣,基本思想是將值存盤為整數中的“美分”。然后,只要您想將值輸出為“美元”,就可以除以 100。(或者具有正確格式化輸出的自定義輸出函式或運算子。)
定點算術的一大好處是可以避免舍入錯誤。浮點數在精確存盤小數方面確實很糟糕,因此處理“十分之一”或“百分之一”很容易導致舍入錯誤,這些錯誤可能會在長時間運行或復雜的程式中累加。
如何實作定點數很大程度上取決于您。您可能會找到一個具有定點類的庫,您可以實作自己的類,或者您可以只操作整數變數。
uj5u.com熱心網友回復:
如果您希望在輸出上發生這種情況,那么您可以使用 setprecision () 方法,因為它設定用于格式化輸出操作上的浮點值的十進制精度。
查找更多https://www.cplusplus.com/reference/iomanip/setprecision/#:~:text=std::setprecision&text=Sets the decimal precision to,input streams or output streams ) .
并檢查這個問題的解決方案
https://www.geeksforgeeks.org/rounding-floating-point-number-two-decimal-places-cc/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/406759.html
標籤:
下一篇:在QML中添加QTreeView
