1

I have this code

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
  struct timeval current_time;
  gettimeofday(&current_time, NULL);
  printf("seconds : %ld\nmicro seconds : %ld\n",
  current_time.tv_sec, current_time.tv_usec);
  char timestamp[100];
  sprintf(timestamp,"%ld.%ld",current_time.tv_sec,current_time.tv_usec);
  printf("timestamp in char:  %s\n", timestamp);
  float timestamp_f;
  timestamp_f = strtold(timestamp,NULL);
  printf("timestamp in float: %10.6f\n",timestamp_f);
  return 0;
}

That returns:

seconds : 1615776760
micro seconds : 957945
timestamp in char:  1615776760.957945
timestamp in float: 1615776768.000000

What happens to the decimals + the last digit is 8 instead of 0?

I used strtof instead, but still got somewhat similar results:

seconds : 1615776930
micro seconds : 767048
timestamp in char:  1615776930.767048
timestamp in float: 1615776896.000000

Thanks.

5
  • 5
    You're converting the values with high precision, then throwing away that precision by converting the result to a single precision float. Don't use float. Use double. Commented Mar 15, 2021 at 3:02
  • So I changed the timestamp_f to a double and the format would be %lf instead of %10.6f. Commented Mar 15, 2021 at 3:08
  • Also "%ld.%ld" --> "%ld.%06ld" Commented Mar 15, 2021 at 3:25
  • %10.6f remains OK. l makes no functional difference in printing. Commented Mar 15, 2021 at 3:27
  • 2
    Don't use strtof as float only has 7 significant digits. You need to use strtold but that functio nreturns a long double so you need to assign it to a variable of that type. Change float timestamp_f; to long double timestamp_f; and make sure your printf specifier is %10.6Lf so that printf knows it is a long double. godbolt.org/z/11Tqqo Commented Mar 15, 2021 at 3:56

2 Answers 2

2

What happens to the decimals + the last digit is 8 instead of 0.

float lacks precision. Use double or long double.

Sign up to request clarification or add additional context in comments.

Comments

0

Make your types agree, such as double and strtod (not strtold). Note that float only has ~7 digits of decimal precision while double is ~16 decimal digits of precision.

double timestamp_f;
timestamp_f = strtod(timestamp,NULL);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.