0

Lets say i have a string "53.430996", I want to convert it to a string and store all the values after the floating point I tried:

#include <iostream>
#include <bits/stdc++.h>
#include <string>
#include <stdlib.h>
using namespace std;
int main(){
   char* convertme="53.430996";
   double converted=atof(convertme);
   cout << converted;
   return 0;
}

But the output is 53.431 but i need 53.430996 so I can later cast it to a long long with

static cast < long long > (coord ∗ 100000)

So, I can get the value without the floating point 5343099

Dave Lee
  • 1
  • 2
  • I recently answered a similar (but not exactly the same) question: https://stackoverflow.com/a/66822431/4641116 and https://stackoverflow.com/a/50970282/4641116 – Eljay Mar 29 '21 at 22:44
  • I'm having trouble understanding. Can you answer it for my code? – Dave Lee Mar 29 '21 at 22:49
  • "So, I can get the value without the floating point 5343099" --> What value did you get with `static cast < long long > (coord ∗ 100000)`? – chux - Reinstate Monica Mar 29 '21 at 23:27
  • If you have a string you may not want to convert it to a double first. You may run into this: [https://stackoverflow.com/questions/588004/is-floating-point-math-broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – drescherjm Mar 29 '21 at 23:59

1 Answers1

1

Just need to make sure you specify the desired precision for fixed point.

#include <iomanip>
#include <iostream>
#include <string>

using std::cout;
using std::stod;
using std::fixed;
using std::setprecision;

int main(){
   auto convertme="53.430996";
   auto converted = stod(convertme);
   cout << fixed << setprecision(6) << converted << "\n";
}
Eljay
  • 4,648
  • 3
  • 16
  • 27