[英]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
您還可以為T
和precision
添加靜態檢查(在編譯時簽名的情況下)。
試試這個,它完美地工作
float=3576.7675745342556;
printf("%.2f",float);
更改其中的一些對象以查看和學習代碼。
yourFloatNumber= Float.Round(yourFloatNumber,2); // In C#
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.