public member function
<ios> <iostream>

std::ios_base::precision

get (1)
streamsize precision() const;
set (2)
streamsize precision (streamsize prec);
獲取/設定浮點數的十進位制精度
第一種形式(1)返回流的當前浮點精度欄位的值。
第二種形式(2)將其設定為新值。

The floating-point precision determines the maximum number of digits to be written on insertion operations to express floating-point values. How this is interpreted depends on whether the floatfield format flag is set to a specific notation (either fixed or scientific) or it is unset (using the default notation, which is not necessarily equivalent to either fixed nor scientific).

對於預設的區域設定
  • 使用預設的浮點數表示法時,精度欄位指定了在插入操作中表示浮點數時要顯示的最大有效數字位數。請注意,它不是最小值,因此如果數字可以用少於*精度*的位數顯示,則不會用尾隨零填充顯示數字。
  • fixedscientific 兩種表示法中,精度欄位都精確指定了小數點後要顯示的位數,即使這包括尾隨的小數零。在這種情況下,小數點前的數字與*精度*無關。

此*十進位制精度*也可以使用引數化運算子 setprecision 進行修改。

引數

prec
浮點數精度的新值。
streamsize 是一個有符號整數值。

返回值

呼叫前的流所選的*精度*。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// modify precision
#include <iostream>     // std::cout, std::ios

int main () {
  double f = 3.14159;
  std::cout.unsetf ( std::ios::floatfield );                // floatfield not set
  std::cout.precision(5);
  std::cout << f << '\n';
  std::cout.precision(10);
  std::cout << f << '\n';
  std::cout.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed
  std::cout << f << '\n';
  return 0;
}

可能的輸出
3.1416
3.14159
3.1415900000


請注意,第一個寫入的數字只有 5 位,而第二個只有 6 位,但不會更多,即使流的精度現在是 10。這是因為帶有預設 floatfieldprecision 只指定了要顯示的*最大*位數,而不是最小位數。
第三個列印的數字顯示小數點後 10 位,因為在這種情況下 floatfield 格式標誌設定為 fixed

資料競爭

訪問(1)或修改(2)流物件。
併發訪問同一個流物件可能導致資料爭用。

異常安全

基本保證:如果丟擲異常,流處於有效狀態。

另見