0

I'm programming a microcontroller in C and since the compiler or chip doesn't handle Floating Point numbers very well, it is recommended to scale the floating point value up enough to get rid of the decimal and then when outputting the number, scale it back down with a proportional division and use modulus to find and display the fractional part. Here's an example: Start with number 25.0625. Multiply by 10000 to get 250625. Good now we don't have a float anymore. Now to display this we use a line like this:

sprintf(buffer, "%li.%i", Temp / 10000, abs(Temp % 10000));

So we first get the 25 back out by / 10000, then we get the 0625 out by % 10000. Here's the problem though: It appears my modulus result ignores the leading zero in 0625 so when it concatenates the number back together, it becomes 25.625 instead of 25.0625. I can't count on there always being a leading zero, so stuffing a zero in there isn't the answer, and there could at other times be several leading zeros. My question is, how do I suppress the modulus from excluding leading zeros ? Thanks.

3
  • 1
    Leading zeros don’t exist numerically; use %04i to format an integer as four digits wide. Commented Oct 3, 2017 at 6:17
  • 1
    Numbers don't have leading zeroes, they're just numbers. You can use %04d format to print it with 4 digits. Commented Oct 3, 2017 at 6:18
  • BTW, sprintf(buffer, "%li.%i", Temp / 10000, abs(Temp % 10000)); is certainly wrong output with Temp = -123. Commented Oct 3, 2017 at 12:55

1 Answer 1

3

You can tell sprintf to format the number in a 4-digit field with leading zeroes.

sprintf(buffer, "%li.%04d", Temp / 10000, abs(Temp % 10000));

See Printing leading 0's in C?

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

8 Comments

Also %.4d does the same job. There are some who argue it is preferred over %04d.
@JonathanLeffler I don't see that recommendation in any of the answers to the question I just linked to.
It does seem to be missing. I’d want to dig up a reference for “there are those who…” before going much further. The x-red is also about zip codes rather than integer/fixed-point arithmetic.
@JonathanLeffler here is a question that discusses the difference, which only affects negative numbers. In my experience, %04d is more idiomatic.
@chux Good point, because integers don't have negative zero for -1234/10000. The code needs to check for this case.
|