KatrinaKing
KatrinaKing

Reputation: 83

convert string to double , the answer is correct ,but not very accurate

I want to use atof to convert my string to a double,the answer is correct ,but not very accurate

ATTENTION: because of some other reasons, fscanf is not permitted

my code is :

#include <stdio.h>
#include <stdlib.h>
#define MAXCN 50

int main(void)
{   FILE* lstm_txt = NULL;
    char lstm_weight[MAXCN] = {0};
    int lstm = 0;
    int i = 0;
    float lstm_val;
    
    if ((lstm_txt = fopen("test1.txt", "r"))== NULL){
        fprintf(stderr,"error:file open failed 'test1.txt'.\n");
        return 1;
    }
    while ((i + 1 < MAXCN) && ((lstm = fgetc(lstm_txt)) != ' ' ) && (lstm != EOF)){
        lstm_weight[i++] = lstm;
    }
    //lstm_weight[i] = 0;
    printf("\n lstm_weight: %s\n\n", lstm_weight);
    lstm_val = atof(lstm_weight);
    printf("\n convert \"lstm_weight\" to lstm_val is : %f\n\n", lstm_val);
    return 0;
 }

my file : lstm_txt is :

4.217959344387054443e-01 -2.566376626491546631e-01 2.173236161470413208e-01 4.217959344387054443e-01

code hasn't bug, and the result is :

 lstm_weight: 4.217959344387054443e-01
 convert "lstm_weight" to lstm_val is : 0.421796

but I want Istm_val is 0.4217959344387054443 ,how can I do that?

Upvotes: -3

Views: 165

Answers (3)

TruVortex_07
TruVortex_07

Reputation: 280

you could try something like sprintf() here's an example:

#include <stdio.h>

int main() {
    char str[50];
    double n = 0.3984092590879;
    sprintf(str, "%lf", n);
    printf(str);
    return 0;
}

prints out:

0.3984092590879

Upvotes: 1

Matteo Pinna
Matteo Pinna

Reputation: 409

Printing %.17f you can have a precision up to 0.42179593443870544

    printf("\n convert \"lstm_weight\" to lstm_val is : %.17f\n\n", lstm_val);

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182763

A double typically has about 15 digits of decimal precision. You will not get more accuracy than that if you store the value in a double. You are getting less because you didn't tell printf how many digits of precision to use for output, so you got the default.

Use something like %0.15f instead of %f.

convert "lstm_weight" to lstm_val is : 0.421795934438705

With %0.20f, I get:

convert "lstm_weight" to lstm_val is : 0.42179593443870544434

That's the best you'll do with a double.

Upvotes: 0

Related Questions