Skip to content

Instantly share code, notes, and snippets.

@slavanap
Created June 28, 2020 13:30
Show Gist options
  • Save slavanap/8434525ab05e796f280aa75fa4a9eac3 to your computer and use it in GitHub Desktop.
Save slavanap/8434525ab05e796f280aa75fa4a9eac3 to your computer and use it in GitHub Desktop.
Decimal to precise float precision cut
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <limits>
using namespace std;
int main() {
char buf [100];
float f1 = (float)0.000000196565025589734432287514209747314453125;
float f2;
sprintf( buf, "%.*e", FLT_DECIMAL_DIG, f1 );
printf("%s\n", buf);
sscanf(buf, "%f", &f2);
printf("%g %g %g %d\n", f1,f2, f1-f2, f1==f2);
stringstream ss;
ss.precision(std::numeric_limits<float>::max_digits10+2);
cout.precision(std::numeric_limits<float>::max_digits10+2);
ss << f1;
ss >> f2;
cout << f1 << endl << f2 << endl << ss.str() << endl << (f1 == f2) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment