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;
}
Lazio
  • 105
  • 1
  • 10

6 Answers6

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.

haccks
  • 104,019
  • 25
  • 176
  • 264
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.

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
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);
//-------^^------------------^^-----------------------------
Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
2

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

Not Amused
  • 942
  • 2
  • 10
  • 28
2
printf("%f is equalled to %.2fcm\n",inches, centimeters);

Note the extra %.2f

Evdzhan Mustafa
  • 3,645
  • 1
  • 24
  • 40
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

Sabbarish
  • 50
  • 8