What is Float to String in C- C Programming Course With Examples

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Strings · Lecture 40

Float to String in C

Print decimals correctly with fixed-point text, rounding and zero padding. A key embedded C programming technique from our free C tutorial.

Sensors report temperature, voltage and pressure as decimals, and your display or log needs text such as “23.45”. Converting a float to a string in C looks easy until you meet the traps: lost leading zeros, rounding errors and, on many embedded toolchains, a printf that does not support %f at all. In this lecture of our free C programming course you will build a dependable fixed-point formatter for embedded C programming, see exactly why the obvious approach prints 3.05 as “3.4”, and learn how to fix it. This lecture is part of our free embedded C course for students and working engineers.

What You Will Learn

  • Why splitting a float into whole and fraction parts goes wrong
  • How binary floating point stores values like 3.05 inexactly
  • How to scale, round and print with leading zeros preserved
  • How to handle negative values and values that round up to the next whole number
  • Why many embedded libraries disable float printf and what to do about it

Prerequisites

You should know integer to string conversion from the previous lecture, the difference between float and int, and basic casts. Both are covered earlier in this free C programming course.

The Obvious Approach and Why It Fails

The tempting method is: take the whole part by casting to int, subtract it, multiply the remainder by a power of ten, and print the two pieces with a dot between them. It fails for two separate reasons.

Problem 1: Leading Zeros Disappear

If the fraction is 0.05 and you scale it to the integer 5, printing it with plain %d gives “3.5”, not “3.05”. The zeros that sit right after the decimal point are lost. You must print the fraction with a fixed width, padded with zeros.

Problem 2: Floats Are Not Exact

Binary floating point cannot store most decimal fractions exactly. The value 3.05 is stored as something slightly below 3.05. Multiply its fraction by 100 and you get 4.99999…, which an integer cast truncates to 4. The result is “3.4” for 3.05, which is plainly wrong.

Why 3.05 can print as 3.4

You write3.05
Stored as3.0499999…
Fraction x 1004.99999…
Cast to int4 (truncated)
Printed with %d“3.4”

Warning: truncation is not rounding. Casting a float to an integer always cuts off the fraction. To round to the nearest value, add 0.5 to a non-negative number before the cast.

The Better Method: Scale First, Then Split

Instead of splitting first and scaling the fraction, we scale the whole number to an integer with rounding, and only then split it using integer division and remainder. Integers are exact, so the split cannot introduce new errors.

StepExample: 3.05 with 2 places
1. Remember the sign, use the magnitude3.05, positive
2. Multiply by 10 to the power places and add 0.5305.4999… + 0.5 = 305.9999…
3. Cast to an unsigned integer305
4. Whole part = scaled / 1003
5. Fraction part = scaled % 1005
6. Print fraction with width 2 and zero padding“05” so the text is “3.05”

The key to step 6 is the format %0*u, where the star lets you choose the width at run time. For two places the width is 2, so 5 becomes “05”.

The Complete Program

#include <stdio.h>
#include <stdint.h>
#include <math.h>

/* naive: fraction digits printed as a plain integer, leading zeros lost */
static void naive(float v)
{
    int whole = (int)v;
    int frac = (int)((v - whole) * 100);
    printf("naive  %-7g -> %d.%d\n", v, whole, frac);
}

/* fixed-point text with 'places' decimals (0..6), rounded to nearest */
int float_to_str(float v, char *buf, size_t cap, unsigned places)
{
    static const uint32_t pow10[] = {1, 10, 100, 1000, 10000, 100000, 1000000};
    if (places > 6)
        return -1;
    int neg = v < 0;
    double mag = neg ? -(double)v : (double)v;
    uint64_t scaled = (uint64_t)(mag * pow10[places] + 0.5);
    uint32_t whole = (uint32_t)(scaled / pow10[places]);
    uint32_t frac  = (uint32_t)(scaled % pow10[places]);

    int n;
    if (places == 0)
        n = snprintf(buf, cap, "%s%u", neg ? "-" : "", (unsigned)whole);
    else
        n = snprintf(buf, cap, "%s%u.%0*u", neg ? "-" : "", (unsigned)whole,
                     (int)places, (unsigned)frac);
    return (n < 0 || (size_t)n >= cap) ? -1 : n;
}

int main(void)
{
    naive(58.5f);
    naive(3.05f);

    float samples[] = {58.5f, 3.05f, -0.25f, 0.007f, 2.999f, 100.0f};
    char b[24];
    for (int i = 0; i < 6; i++) {
        float_to_str(samples[i], b, sizeof b, 2);
        printf("fixed  %-7g -> %s\n", samples[i], b);
    }
    float_to_str(58.5f, b, sizeof b, 4);
    printf("4 places: %s\n", b);
    return 0;
}

Build and Run

$ gcc -std=c11 -Wall -Wextra -o fix fix.c -lm
$ ./fix

Expected Output

naive  58.5    -> 58.50
naive  3.05    -> 3.4
fixed  58.5    -> 58.50
fixed  3.05    -> 3.05
fixed  -0.25   -> -0.25
fixed  0.007   -> 0.01
fixed  2.999   -> 3.00
fixed  100     -> 100.00
4 places: 58.5000

The naive version gets 58.5 right by luck, because 0.5 is exactly representable in binary, and gets 3.05 wrong. The fixed version handles both, plus a negative value, a value that rounds down to 0.01, and a value (2.999) that rounds up into the next whole number and correctly shows 3.00.

Walking Through the Code

Sign Handling

We record neg and work on the magnitude. That avoids the awkward case where the whole part is zero and the sign would otherwise disappear: -0.25 has a whole part of 0, and “0.25” without the minus sign would be a serious bug. Printing the sign separately keeps it.

Scaling and Rounding

We use a double for the multiplication so a large scale does not lose precision, and a 64-bit integer for the scaled result so large readings with several decimal places do not overflow. The + 0.5 turns the final truncating cast into round-to-nearest.

Carry Happens for Free

Because we split after rounding, the case 2.999 turns into 300 and splits cleanly into 3 and 00. The older method of rounding the fraction on its own can produce “2.100” style bugs when the fraction rounds up to a full unit.

Buffer Safety

snprintf never writes past the capacity and returns the length it wanted. We treat a result that does not fit as an error and return -1.

Embedded Reality: Printf Without Float

Many embedded libraries, such as newlib-nano used with ARM GCC, build printf without floating point support to save space. On those targets %f prints nothing useful or an empty field unless you enable a special linker option, which adds many kilobytes. The routine above uses only integer formatting in the final step, so it works everywhere.

ApproachFlash costExact?Best for
printf with %fhighfine for displayPC tools, large MCUs
Scale, round, split (this lecture)lowexact to chosen placessmall MCUs, logs, LCDs
Fixed-point integers everywherelowestexactno FPU, high reliability

Design Tip

If your sensor already delivers integers, such as temperature in hundredths of a degree, never convert to float at all. Keep it as an integer and split it with / 100 and % 100. It is faster, smaller and has no rounding surprises.

Real-World Use Cases

  • LCD and OLED readouts of temperature, voltage and humidity.
  • Telemetry strings sent over UART or Bluetooth.
  • Data logging to SD cards in text or CSV format.
  • Calibration tools where printing the exact decimals matters.

Common Mistakes

  • Printing the fraction with %d, losing leading zeros.
  • Truncating instead of rounding.
  • Dropping the sign when the whole part is zero.
  • Comparing floats with == in tests. Use a tolerance.
  • Assuming printf supports %f on every embedded toolchain.
  • Using too many places. A float holds only about 7 significant decimal digits.

Best Practices

  • Choose the number of decimal places deliberately, based on sensor accuracy.
  • Scale and round before splitting.
  • Prefer integer or fixed-point data when no FPU is present.
  • Test with values like 0.05, 0.007, 2.999, negative numbers and whole numbers.
  • Check the length returned by snprintf every time.

Suggested Images

Image ideaSuggested ALT text
Diagram showing 3.05 stored as 3.0499999float to string in C rounding problem explained, free C programming course
Scale, round, split flow chartfixed point float formatting in embedded C programming, free C tutorial
LCD showing a temperature readingprinting sensor values without float printf, free embedded C course

Summary and Key Takeaways

  • Splitting a float first and scaling the fraction loses zeros and accuracy.
  • Scale the whole value, round, then split with integer division and remainder.
  • Print the fraction with zero padding using %0*u.
  • Handle the sign separately so values like -0.25 keep their minus.
  • Integer or fixed-point data avoids float printing entirely.

Conclusion

You now have a float to string routine that prints exactly the decimals you ask for and works even when the library has no float support. You also understand why floating point behaves oddly, which will save you hours of debugging in real embedded C programming. The next and final lecture of this chapter revisits common string mistakes and ends with a quiz and interview questions.

Frequently Asked Questions

Why does 3.05 print as 3.4 with the naive method?

3.05 is stored slightly below its true value. Multiplying the fraction gives 4.999…, and the integer cast truncates it to 4.

Is there a standard library function for this?

snprintf with %f works on most systems. On small embedded builds it may be disabled, which is why a manual routine is useful.

What does %0*u mean?

It prints an unsigned value padded with zeros to a width taken from an extra int argument.

Why use double in the multiplication?

It keeps more precision when scaling by large powers of ten before converting to an integer.

How many decimal places can a float hold?

Roughly seven significant digits in total, so printing more places than the value really has just prints noise.

Should I avoid float on microcontrollers?

Not always, but on parts without a floating point unit it is slow and large. Fixed-point integers are often a better fit.

Keep Learning with the Free C Programming Course

Next up: common string pitfalls, a quiz and interview questions to finish the Strings chapter.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →