Floating-Point Types - C Language Basics

C examples for Language Basics:Variable

Introduction

The floating-point types can store real numbers with different levels of precision.

Demo Code

#include <stdio.h>

int main() {//from  w w w.  ja v  a2s  . c o m
    float myFloat;    /* ~7 digits */
    double myDouble;  /* ~15 digits */
    long double myLD; /* typically same as double */
}

A float can accurately represent about 7 digits.

A double can handle around 15 of them.

Demo Code

#include <stdio.h>

int main() {/*  w  w w.j a  v a 2  s  . co m*/
    float myFloat = 12345.678;
    printf("%f", myFloat); /* "12345.677734" */
}

Result

You can limit the decimal places to two in the following way.

Demo Code

#include <stdio.h>

int main() {/*from  w w  w. j  av a2 s  .co m*/
    float myFloat = 12345.678;

    printf("%.2f", myFloat); /* "12345.68" */
}

Result

Floating-point numbers can be expressed using decimal, exponential, or hexadecimal notation.

Exponential scientific notation is used by adding E or e followed by the decimal exponent.

The hexadecimal floating-point notation uses P or p to specify the binary exponent.

Demo Code

#include <stdio.h>

int main() {/*  ww  w.j  a  v  a  2s  .  com*/
    float myFloat = 12345.678;

    double fDec = 1.23;
    double fExp = 3e2;   /* 3*10^2 = 300 */
    double fHex = 0xAA2; /* 10*2^2 = 40 */
}

Related Tutorials