Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C Type Conversion

Sometimes a value of one type is used where another type is expected: an int is stored in a double, or a double in an int. C then converts the value. Some conversions happen by themselves; others you write on purpose.

Automatic conversion

When a value is stored in a variable of another type, C converts it. From int to double nothing is lost. From double to int the decimal part is cut off (not rounded), and the compiler may warn.

#include <stdio.h>

int main(void) {
    int whole = 9;
    double d = whole;      // 9 becomes 9.0
    double price = 9.99;
    int cut = (int)price;  // the decimals are dropped
    printf("d = %.1f\n", d);
    printf("cut = %d\n", cut);
    return 0;
}
Output
d = 9.0
cut = 9

In a calculation that mixes types, C converts the "smaller" type to the "bigger" one first: in 5 + 2.5, the 5 becomes 5.0 and the result is the double 7.5.

The integer division trap

If both values are integers, the result is an integer, even when you store it in a double. The conversion happens too late:

#include <stdio.h>

int main(void) {
    int total = 7, count = 2;
    double wrong = total / count;           // 7 / 2 is 3, then 3.0
    double right = (double)total / count;   // 7.0 / 2 is 3.5
    printf("wrong: %.2f\n", wrong);
    printf("right: %.2f\n", right);
    return 0;
}
Output
wrong: 3.00
right: 3.50

Casting

Writing a type in brackets before a value, such as (double)total, converts it on purpose. This is called a cast. Use it when you need decimals from integers, or to show the reader that dropping the decimals is intended, as in (int)price.

To round instead of cutting off, use round from math.h, or add 0.5 before cutting positive numbers:

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

int main(void) {
    double x = 7.6;
    printf("cast:  %d\n", (int)x);
    printf("round: %.0f\n", round(x));
    printf("plus 0.5 then cast: %d\n", (int)(x + 0.5));
    return 0;
}
Output
cast:  7
round: 8
plus 0.5 then cast: 8

Characters and numbers

A char is a small number, so converting between them is easy: '7' - '0' is the number 7, which is how a program turns a digit character into its value.

Practice exercises

  1. Compute the average of the marks 81, 77 and 90 with two decimals.
  2. Convert 98.6 degrees Fahrenheit to Celsius with (f - 32) * 5 / 9 and print it. Is the result right with integers? Fix it.
  3. Print the number value of the character '9' minus '0'.