catof

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?


Solution

  • 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);