Formatting a float using snprintf()

3 posts / 0 new
Last post
trixie
trixie's picture
Offline
Last seen: 7 months 4 weeks 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
thomas's picture
Offline
Last seen: 1 week 6 days 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);
trixie
trixie's picture
Offline
Last seen: 7 months 4 weeks ago
Joined: 2011-02-03 13:58
Re: Formatting a float using snprintf()

@thomas

Thanks for the tip, works very well! And I can use IUtility->SNPrintf(), too :-)

AmigaOne X5000-020 / 2GB RAM / Sapphire Pulse Radeon RX 560 / AmigaOS 4.1 Final Edition Update 2

Log in or register to post comments