1

I don't know what I am doing wrong but I want to convert a string to a double, using std::stod, but it chops of the decimal points

int main()
{
  auto value = std::string("321415.1342");
  auto val = std::stod(value, 0);
  std::cout << val << '\n';
}

this program produces: 321415. The stof also produces the same result. My locale is listed below if it helps.

LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
Ring Zero.
  • 459
  • 3
  • 12

1 Answers1

2

You need to alter the precision. std::setprecision and std::fixed are what you are looking for. You have to include iomanip:

#include <iostream>
#include <string> 
#include <iomanip>  // <- include this

int main()
{
  auto value = std::string("321415.1342");
  auto val = std::stod(value, 0);
  std::cout << std::setprecision(5) << std::fixed << val << std::endl;

  return 0;
}

Output:

321415.13420

See this answer for more on the topic.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93