简体   繁体   中英

Reading float value from string upto 6 precision

i have to read a flot value from string up to 6 precision , Current code is reading first 6 digits only. Thanks in Advance

template <class T>
bool from_string(T& t,    const std::string& s, 
                 std::ios_base& (*f)(std::ios_base&))
{
  std::istringstream iss(s);
  return !(iss >> f >> t).fail();
}

int main()
{
  int i;
  float f;
 // the third parameter of from_string() should be 
  // one of std::hex, std::dec or std::oct
  if(from_string<int>(i, std::string("ff"), std::hex))
  {
    std::cout << i << std::endl;
  }
  else
  {
    std::cout << "from_string failed" << std::endl;
  }

  if(from_string<float>(f, std::string("1456.909"), std::dec))
  {
    std::cout << f << std::endl;
  }
  else
  {
    std::cout << "from_string failed" << std::endl;
  }
  return 0;
} 

I'm quite certain it's reading all digits. The problem appears to be in what you expect. Let's put it a bit stronger: What would you expect to happen if you read 1456.90900000000000000000000000000 in a float ?

You need to use a double, rather than a float if you want to do better than 6 digits. Your question says "6 digits of precision" and also "first 6 digits" but you're presenting input which is 7 digits.

The float can only hold 6 digits precision iexyzpqrs or xy.zpqrs or xyzpq.rs. If you're after holding 6 decimal places then you need to use double.

You can make it output more decimal places by using cout.precision(7) for instance, which in this case will print the right answer, even though C isn't actually storing 7 digits, just something that approximates to the right answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM