基于双函数的字符串精度

precision of double function based string

本文关键字:字符串 精度 函数 于双      更新时间:2023-10-16

假设你有一个函数:

string function(){
double f = 2.48452
double g = 2
double h = 5482.48552
double i = -78.00
double j = 2.10
return x; // ***
}

* 对于 x,我们插入:

if we will insert f, function returns: 2.48
if we will insert g, function returns: 2
if we will insert h, function returns: 5482.49
if we will insert i, function returns:-78
if we will insert j, function returns: 2.1

他们只是例子,谁展示了 funcion() 是如何工作的。准确地说:双 k 返回函数将其四舍五入为:k.XX,但对于:k=2.20它返回 2.2 作为字符串。它是如何实现的?

1)仅仅因为您看到两位数,并不意味着基础值必须四舍五入到两位数。

的精度和格式化输出中显示的位数是两个完全不同的东西。

2)如果你使用的是cout,你可以用"setprecision()"控制格式:

http://www.cplusplus.com/reference/iomanip/setprecision/

示例(来自上面的链接):

// setprecision example
#include <iostream>     // std::cout, std::fixed
#include <iomanip>      // std::setprecision
int main () {
  double f =3.14159;
  std::cout << std::setprecision(5) << f << 'n';
  std::cout << std::setprecision(9) << f << 'n';
  std::cout << std::fixed;
  std::cout << std::setprecision(5) << f << 'n';
  std::cout << std::setprecision(9) << f << 'n';
  return 0;
}

示例输出:

3.1416
3.14159
3.14159
3.141590000

在数学上,2.22.202.2002.2000等完全相同。如果要查看更多无关紧要的零,请使用[setprecision][1]

cout << fixed << setprecision(2);
cout << 2.2 << endl; // Prints 2.20

要显示最多 2 位小数,但不显示尾随零,您可以执行以下操作:

std::string function(double value)
{
  // get fractional part
  double fracpart = value - static_cast<long>(value);
  // compute fractional part rounded to 2 decimal places as an int
  int decimal  = static_cast<int>(100*fabs(fracpart) + 0.5);
  if (decimal >= 100) decimal -= 100;
  // adjust precision based on the number of trailing zeros
  int precision = 2; // default 2 digits precision
  if      (0 ==  decimal)       precision = 0; // 2 trailing zeros, don't show decimals
  else if (0 == (decimal % 10)) precision = 1; // 1 trailing zero, keep 1 decimal place
  // convert value to string
  std::stringstream str;
  str << std::fixed << std::setprecision(precision) << value;
  return str.str();
}