What you want is %.2f, not 2%f.

Also, you might want to replace your %d with a %f ;)

#include <cstdio>
int main()
{
printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
return 0;
}

This will output:

When this number: 94.945600 is assigned to 2 dp, it will be: 94.95

See here for a full description of the printf formatting options: printf

Answer from badgerr on Stack Overflow
🌐
W3Schools
w3schools.com › c › c_data_types_dec.php
C Data Types Decimal Precision
If you want to remove the extra zeros (set decimal precision), you can use a dot (.) followed by a number that specifies how many digits that should be shown after the decimal point: float myFloatNum = 3.5; printf("%f\n", myFloatNum); // Default ...
🌐
Oxford University
mathcenter.oxford.emory.edu › site › cs170 › printf
The printf Method
we now see that the format specifier "%.2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places.
Discussions

Printf Questions - Floating Point
Not printing any decimal places is not very user friendly, you'd be forced to specify a higher limit every time you want to see any decimal places (which you probably want when you use a float). The maximum is also not very useful since it's going to be way too much. Six is a good middle ground and a good default if the user doesn't care too much. It could probably just as easily have been 5 or 7. More on reddit.com
🌐 r/C_Programming
12
5
September 13, 2025
c - Is there a way to automatically printf a float to the number of decimal places it has? - Stack Overflow
I've written a program to display floats to the appropriate number of decimal places: #include int main() { printf("%.2f, %.10f, %.5f, %.5f\n", 1.27, 345.1415926535, 1. More on stackoverflow.com
🌐 stackoverflow.com
floating point - 'printf' a float value in C - Stack Overflow
I want to print a float value which has two integer digits and six decimal digits after the comma. If I just use printf("%f", myFloat), I'm getting a truncated value. I don't know if this More on stackoverflow.com
🌐 stackoverflow.com
c - Using printf() to output the correct number of decimal places - Stack Overflow
When I enter 2, I wish to get this output: value: 2.4 But when I do the multiplication, I am getting this: value: 2.400000 This is my code: #include int main() { float num; f... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

Can I truncate instead of round with printf?
The C standard library's printf function will always perform rounding when formatting to a specific precision limit. If strict truncation (chopping off decimals without rounding up) is required, developers must apply math functions like floor() or cast the multiplied value to an integer prior to formatting.
🌐
technetexperts.com
technetexperts.com › home › [solved] how to format float decimal places in c printf
[Solved] How to Format Float Decimal Places in C printf
Why does float arithmetic sometimes yield unexpected results?
Floating-point numbers in C follow the IEEE 754 standard, which represents decimals in binary fractions. Since certain decimal numbers (like 1.2) cannot be represented exactly in binary, minor precision artifacts occur. The printf function's precision modifier applies standard rounding to present these numbers cleanly to users.
🌐
technetexperts.com
technetexperts.com › home › [solved] how to format float decimal places in c printf
[Solved] How to Format Float Decimal Places in C printf
What is the difference between %f and %lf?
The %f specifier is traditionally used for floats, while %lf is used for doubles. However, in modern C standards, variadic functions like printf automatically promote float arguments to double. Therefore, %f will technically work for both in output, but %lf remains strictly required when reading doubles via scanf.
🌐
technetexperts.com
technetexperts.com › home › [solved] how to format float decimal places in c printf
[Solved] How to Format Float Decimal Places in C printf
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › Format-double-Java-printf-example
How to format a Java double with printf
%f formats floating-point values such as float and double. %d is for integral values such as byte, short, int and long. double price = 19.95; int quantity = 4; System.out.printf("Price: %.2f%n", price); System.out.printf("Quantity: %d%n", quantity);
Published: March 30, 2026
🌐
TechNetExperts
technetexperts.com › home › [solved] how to format float decimal places in c printf
[Solved] How to Format Float Decimal Places in C printf
July 23, 2026 - The conditions for this behavior require declaring floating-point variables, reading an integer or floating input, performing arithmetic, and rendering the result with the default %f token. When the input provided is 2, the developer will see the exact output string value: 2.400000 rather than the requested value: 2.4. The following code snippet demonstrates the exact conditions that reproduce this formatting behavior: To fix this output and enforce strict decimal place limits, developers must utilize the precision modifier within the format string.
🌐
Reddit
reddit.com › r/c_programming › printf questions - floating point
r/C_Programming on Reddit: Printf Questions - Floating Point
September 13, 2025 -

I am reading The C programming Language book by Brian W. Kernighan and Dennis M. Ritchie, I have a few questions about section 1.2 regarding printf and floating points.

Question 1:

Example:

Printf("%3.0f %6.1f \n", fahr, celsius); prints a straight forward answer:

0 -17.8

20 -6.7

40 4.4

60 15.6

However, Printf("%3f %6.1f \n", fahr, celsius); defaults to printing the first value as 6 decimal points.

0.000000 -17.8

20.000000 -6.7

40.000000 4.4

60.000000 15.6

Q: Why when not specifying the number of decimal points required does it default to printing six decimal points and not none, or the 32-bit maximum number of digits for floating points?

Question 2:

Section 1.2 also mentions that if an operation consists of a floating point and an integer, the integer is converted to floating point for that operation.

Q: Is this only for this operation? Or is it for all further operations within the scope of the function? I would assume only for that one specific operation in that specific function?

If it is in a loop, is it converted for the entire loop or only for that one operation within the loop?

Example:

void function (void)

  int a;
  float b;

  b - a //converts int a to float during operation

  a - 2 //is int a still a float or is it an integer?
Find elsewhere
🌐
Smith College
science.smith.edu › ~jfrankli › 231f13 › 231 › format.html
Formatting in printf, in C
You can control the number of digits after the decimal point when printing a floating point value using printf.
🌐
IncludeHelp
includehelp.com › c › how-to-print-float-value-till-number-of-decimal-points-using-printf.aspx
How to print float value till number of decimal points using printf in C language?
Given a float value and we have to print the value with specific number of decimal points. Consider the given code, here we have a float variable named num and its value is "10.23456". #include <stdio.h> int main() { float num = 10.23456f; printf("num = %f\n",num); return 0; }
Top answer
1 of 2
4

Is there a way to automatically printf a float to the number of decimal places it has?

Use "%g". "%g" lops off trailing zero digits.

... unless the # flag is used, any trailing zeros are removed from the fractional portion of the result and the decimal-point character is removed if there is no fractional portion remaining. C17dr § 7.21.6.1 8.

All finite floating point values are exactly representable in decimal - some need many digits to print exactly. Up to DBL_DECIMAL_DIG from <float.h> (typically 17) significant digits is sufficient - rarely a need for more.

Pass in a precision to encourage enough output, but not too much.

Remember values like 0.00008 are not exactly encoded in the typical binary floating point double, but a nearby value is used like 8.00000000000000065442...e-05

printf("%.*g\n", DBL_DECIMAL_DIG, some_double);

printf("%.17g, %.17g, %.17g, %.17g\n", 1.27, 345.1415926535, 1.22013, 0.00008);
// 1.27, 345.14159265350003, 1.2201299999999999, 8.0000000000000007e-05

DBL_DIG (e.g. 15) may better meet OP's goal.

printf("%.15g, %.15g, %.15g, %.15g\n", 1.27, 345.1415926535, 1.22013, 0.00008);
// 1.27, 345.1415926535, 1.22013, 8e-05

Function to print a double - exactly may take 100s of digits.

2 of 2
-1

sprintf() could help you
There is no direct way to do this in my experience
here is a simple algorithm to help you with this function

munber = float/double input
n = number of decimal places in float/double
char format[999];
sprintf(format ,"%%.%df" ,n);
printf(format, number);

sprintf is like printf but instead of writing to stdout, sprintf writes to a string.

Now you are left with finding number of digits after the precision.

Top answer
1 of 1
1

You can specify how many digits you want to print after the decimal point by using %.Nf where N is the number of digits after the decimal point. In your use case, %.1f: printf("Result: %.1f", result).


There are some other issues in your code. You are making use of scanf(), but you are not checking its return value. This may cause your code to break.

scanf() returns the number of arguments it successfully parsed. If, for any reason, it fails, it doesn't alter the arguments you gave it, and it leaves the input buffer intact. This means whenever you try again and read from the input buffer, it will automatically fail since

  • it previously failed to parse it, and
  • it didn't clear it, so it's always there.

This will result in an infinite loop.

To solve the issue, you need to clear the input buffer in case scanf() fails. By clearing the buffer, I mean read and discard everything up until a newline (when you previously pressed Enter) is encountered.

void getfloat(const char *message, float *f)
{
    while (true) {
        printf("%s: ", message);
        int rc = scanf("%f", f);
        if (rc == 1 || rc == EOF) break; // Break if the user entered a "valid" float number, or EOF is encountered.
        scanf("%*[^\n]"); // Read an discard everything up until a newline is found.
    }
}

You can use it in your main like that:

int main(void) // Note the void here when a function doesn't take any arguments
{
    float num;
    float result;
    
    getfloat("Number", &num);
    
    result = num * 1.2;
    printf("Result: %.1f", result); // Print only one digit after the decimal point.
}

Sample output:

Number: x
Number: x12.45
Number: 12.75
Result: 15.3
🌐
GeeksforGeeks
geeksforgeeks.org › c language › g-fact-41-setting-decimal-precision-in-c
Setting decimal precision in C - GeeksforGeeks
January 10, 2025 - ... // C program to set precision in floating point numbers // using format specifier #include<stdio.h> int main() { float num = 5.48958123; // 4 digits after the decimal point printf("%0.4f", num); return 0; }
🌐
Northern Michigan University
nmu.edu › Webb › ArchivedHTML › MathComputerScience › c_programming › c_008.htm
More About Float and Double Variables
#include <stdio.h> main() { int ... 11.000000e23 · To change the number of decimal places printed out for float or double variables, modify the %f or %e to include a precision value, eg,...
Top answer
1 of 1
17

Use ".*"

printf("%.*f", precision, f);

Example:

>>> printf("%.*f", 5, 3.14)
"3.14000"

Precision

This is called the precision field. According to the man pages,

The precision: An optional precision, in the form of a period ('.') followed by an optional decimal digit string. Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the precision is given in the next argument, or in the m-th argument, respectively, which must be of type int. If the precision is given as just '.', or the precision is negative, the precision is taken to be zero. This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the radix character for a, A, e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, or the maximum number of characters to be printed from a string for s and S conversions.

Width

The width field is similar and works for more formats, such as "%*s". Just remove the .. It will pad the output with spaces or zeros as needed. If precision is negative, the string will be left-aligned.

>>> printf("%*s\n", 10, "left?")
"     left?"
>>> printf("%*s\n", -10, "left?")
"left?     "

According to the man pages,

The field width: An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int. A negative field width is taken as a '-' flag followed by a positive field width. In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

🌐
Cplusplus
cplusplus.com › reference › cstdio › printf
Printf
C string that contains the text to be written to stdout. It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested. A format specifier follows this prototype: [see compatibility note below] · ...
🌐
Caltech
sites.astro.caltech.edu › ~mcs › ovro › 40m › help › DoubleFormat.html
A floating point format specifier.
In this case formal specifiers are are written in place as the first arguments of the $format_double() function. The syntax of the format specifiers. The format specifier strings are a subset of the double precision formats accepted by the C language printf function, plus an extra "s" style, ...
🌐
TechNetExperts
technetexperts.com › home › how to print float with 6 decimal places in c [fixed]
How to Print Float with 6 Decimal Places in C [Fixed]
July 21, 2026 - Yes, C allows dynamic precision using the asterisk syntax. By writing printf("%.*f", 6, myFloat);, the integer preceding the float in the argument list dictates the number of decimal places.
🌐
Iveselov
notes.iveselov.info › programming › printf-and-floating-point-numbers
printf() and floating point numbers | IV Notes
March 22, 2020 - So now we can see that it's completely fine to have so many digits from printf and we also have an upper bound on them. For example in our case we should expect no more than 53 + 4 digits after the point. "+4" because we use -4 exponent, which can add more digits. Indeed, if we add some more precision to our original program, we can see that decimal representation of our double has 56 digits (and zeros after that): A tool to explore floating point numbers, where you can toggle bits and see how it affects the value, inspect decimal representations and do many other things