這篇文章將討論如何在 C++ 中將浮點值限制為小數點後兩位。
1.使用 round()
功能
有幾個選項可以將浮點數限制為兩位小數,具體取決於您是否希望將數字四捨五入到最接近、向下舍入或向上舍入。例如,以下代碼將浮點數四捨五入到小數點後兩位。
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <cmath> int main() { float f = 10.517986; float value = round(f * 100) / 100; std::cout << value << std::endl; // 10.52 return 0; } |
要將雙精度數舍入到小數點後 2 位,您可以使用 std::ceil
功能如下:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <cmath> int main() { float f = 10.517986; float value = floor(f * 100) / 100; std::cout << value << std::endl; // 10.51 return 0; } |
要將雙精度數舍入到小數點後 2 位,您可以使用 std::ceil
功能如下:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <cmath> int main() { float f = 10.517986; float value = ceil(f * 100) / 100; std::cout << value << std::endl; // 10.52 return 0; } |
2.使用 std::ios_base::precision
這 std::ios_base::precision
函數用於設置流的浮點值的小數精度。你可以使用 std::ostringstream
與精度說明符為 std::cout
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <sstream> std::string format(float f, int digits) { std::ostringstream ss; ss.precision(digits); ss << f; return ss.str(); } int main() { float f = 10.517986; int digits = 4; std::string value = format(f, digits); std::cout << value << std::endl; // 10.52 return 0; } |
如果您只需要將格式化的字符串寫入控制台,請執行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <cmath> int main() { float d = 10.517986; std::cout.precision(4); std::cout << d << std::endl; // 10.52 return 0; } |
使用 C,您可以使用 %.2f
中的格式字符串 printf()
功能。
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <cmath> int main() { float f = 10.517986; printf("%.2f", f); // 10.52 return 0; } |
這就是在 C++ 中將浮點值限制在小數點後兩位。