Reputation: 85
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
Upvotes: 2
Views: 125
Reputation: 7352
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.
Upvotes: 2
Reputation: 234645
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>
.
Upvotes: 7