简体   繁体   中英

convert time into millisecond in C

I have a list of data formatted as

08:01:00.064

Notation: hour,minute,second and millisecond

I need convert them into the notation of: second.millisecond.

Please find my code below,

float calculateTime(char *line) {

    int hour;
    int minute;
    int second;
    int millisecond;
    //transfer from char to int
    hour = ((line[0] - '0')*10 + (line[1] - '0'))*3600;
    minute = ((line[3] - '0')*10 + (line[4] - '0'))*60;
    second = (line[6] - '0')*10 + (line[7] - '0');
    millisecond = (line[9] - '0') *100 + (line[10] - '0') *10 + (line[11] - '0');

    float time;

    time = hour + minute + second + millisecond *0.001;

    return (time);

}

There is a problem with my code that the milliseconds will be inaccurate. I think it's due to the float format when calculating.

Result below,

37831.945312 source millisecond = 944

The output I expected was

37831.945312

A typical float (IEEE754 32 bit) will only be accurate to about 7 significant digits. You exceed that.

A solution? Use a double instead. That will give you about 15 significant figures. But note that the result may well still not be exact . That's the nature of floating point arithmetic.

A decent solution? Use a stuct instead containing the time values. There's one called tm in <time.h> .

Your problem lies with the lack of precision in the 32 bit float type. Use type double instead for the time variable. It has the precision you require.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM