1

I've wrote this simple program which converts inches to centimetres but the float gives me some huge numbers after the decimal place. I want it to look more like for example 25.78 rather than 25.780000 or something. What should I change to make it look like that? Here is the program:

#include <stdio.h>

int main()
{
    float inches, centimeters;

    printf("Enter a number of inches to be converted: ");
    scanf(" %f", &inches);

    centimeters = inches * 2.54;        // 1 inch = 2.54cm

    printf("%f is equalled to %fcm\n",inches, centimeters);

    return 0;
}
5
  • %.2f rather than %f in the printf statement will do it.
    – enhzflep
    Mar 26, 2014 at 16:13
  • possible duplicate of C: printf a float value
    – Not Amused
    Mar 26, 2014 at 16:14
  • More info about formating strings in C: codingunit.com/…
    – adripanico
    Mar 26, 2014 at 16:15
  • try %g instead of %f.
    – BLUEPIXY
    Mar 26, 2014 at 16:16
  • 1
    @user2938819 - There are several good answers below. if you see one that works for you, acknowledge it by clicking the hollow check mark or an up arrow.
    – ryyker
    Mar 26, 2014 at 16:28

6 Answers 6

2

Add a precision to your format specifier in printf:

printf("%.2f is equalled to %.2f cm\n", inches, centimeters);

%.2f means your value will have a precision of 2 places after the decimal point.

2

Change the format a bit - instead of using "%f" use ".2%f.

Like

//-------vv------ and -------vv-----------------------------
printf("%.2f is equalled to %.2fcm\n",inches, centimeters);
//-------^^------------------^^-----------------------------
2

printf("%.2f", myFloat); 2 represents number of digits after decimal point

2
printf("%f is equalled to %.2fcm\n",inches, centimeters);

Note the extra %.2f

2

Use %.2f in your printf.

printf("%.2f is equalled to %.2fcm\n",inches, centimeters); 

and must read Basics of Formatted Input/Output in C.

1

printf("%f is equalled to %.2fcm\n",inches, centimeters);

U can write %.2f if u need the precision to be 2.

Read these articles: http://www.cplusplus.com/reference/cstdio/printf/

http://www.cs.fsu.edu/~myers/c++/notes/c_io.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.