Skip to content

Commit

Permalink
Fixed bug in parsing floating point numbers with more than 15 decimal…
Browse files Browse the repository at this point in the history
… places.
  • Loading branch information
agudys committed Aug 19, 2024
1 parent c97b113 commit 52a4863
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 9 deletions.
51 changes: 44 additions & 7 deletions src/conversion.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,19 @@
#include <limits>
#include <cmath>

#include <iostream>
#include <iomanip>

// ************************************************************************************
class Conversions
{
public:
static const int POWERS_SIZE = 15;
static uint64_t powers10[POWERS_SIZE];
static double neg_powers10[POWERS_SIZE];

static char digits[100000 * 5];
static uint64_t powers10[15];
static double neg_powers10[15];

struct _si {
_si()
{
Expand All @@ -44,7 +50,7 @@ class Conversions

powers10[0] = 1;
neg_powers10[0] = 1.0;
for (int i = 1; i < 15; ++i) {
for (int i = 1; i < POWERS_SIZE; ++i) {
powers10[i] = 10 * powers10[i - 1];
neg_powers10[i] = 0.1 * neg_powers10[i - 1];
}
Expand Down Expand Up @@ -171,14 +177,17 @@ class Conversions
}
if (*p == '.') {
double f = 0.0;
int n = 0;
//int n = 0;
++p;
double mul = 1.0;
while (*p >= '0' && *p <= '9') {
f = (f * 10.0) + (*p - '0');
++p;
++n;
//++n;
mul *= 0.1;

}
r += f * neg_powers10[n];
r += f * mul;
}

// optional exponential part
Expand All @@ -197,7 +206,12 @@ class Conversions
exp = exp * 10 + (*p++ - '0');
}

r *= exp_neg ? neg_powers10[exp] : powers10[exp];
if (exp < POWERS_SIZE) {
r *= exp_neg ? neg_powers10[exp] : powers10[exp];
}
else {
r *= exp_neg ? pow(10, -exp) : pow(10, exp);
}
}

if (neg) {
Expand All @@ -210,6 +224,29 @@ class Conversions

return r;
}

static void test_strtod() {

const char* strings [] = {
"123",
"0.123",
"123.456",
"12345678987654321",
"0.12345678987654321",
"123456789.12345678987654321",
"12345678987654321.12345678987654321",
"1.23e2",
"1.23e-2",
"123e20",
"123e-20"
};

for (const auto& s : strings) {
char* end;
double v = strtod(s, &end);
std::cout << std::setprecision(15) << v << std::endl;
}
}
};


Expand Down
16 changes: 14 additions & 2 deletions src/version.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,17 @@
//
// *******************************************************************************************

#define VERSION "1.0.0"
#define DATE "2024-06-26"
#define VERSION "1.0.1"
#define DATE "2024-08-19"


/********* Version history *********
1.0.1 (2024-08-19)
Fixed bug in parsing floating point numbers with more than 15 decimal places.
1.0.0 (2024-06-26)
First public release
*/

0 comments on commit 52a4863

Please sign in to comment.