Formatting a float using snprintf()

3 posts / 0 new
Last post
trixie's picture
Last seen: 1 month 1 week ago
Joined: 2011-02-03 13:58
Formatting a float using snprintf()

I'm trying to produce a formatted string that shows the length of an audio sample. The format I want is HH:MM:SS.MS, where SS.MS is a float containing seconds and (after the decimal point) milliseconds.

For example "00:23:22.54" (23 minutes, 22 seconds and 54 milliseconds).

I'm using snprintf() from newlib, the call is this:

snprintf(buffer, sizeof(buffer), "%02ld:%02ld:%02.2f", hours, minutes, secondsF);

"hours" and "minutes" are integers, "secondsF" is a float number.

But for some reason, if the number of seconds is < 10 the string comes out for example as "00:00:1.48" instead of "00:00:01.48". Is it a bug in the sprintf() implementation, or am I doing anything wrong?

Is there a workaround I could use?

(I tried using IUtility->SNPrintf() but it's even more limited and doesn't support formatting floats at all.)

thomas's picture
Last seen: 1 day 6 hours ago
Joined: 2011-05-16 14:23
Re: Formatting a float using snprintf()

I would avoid formatting floats at all.

  1. snprintf(buffer, sizeof(buffer), "%02ld:%02ld:%02ld.%02ld", hours, minutes, (long)secondsF, ((long)(secondsF * 100.0)) % 100);
Log in or register to post comments