← Back to C Course | Chapter 1: Introduction & Basics | Lesson 12 of 21

C Decimal (Floating-Point) Numbers

Decimal numbers require a floating-point type like float or double, since integer types can only store whole numbers, and double is the standard choice offering roughly twice float's precision.

What are Decimal (Floating-Point) Numbers?

Decimal numbers, also called floating-point numbers, represent values with a fractional part and require a type like float or double, since int and other integer types can only store whole numbers.

Example: What are Decimal (Floating-Point) Numbers?

c
#include <stdio.h>
int main() {
	float price = 9.99f;
	printf("%.2f", price);
	return 0;
}

float Precision

float is a single-precision floating-point type that typically stores about 6 to 7 significant decimal digits accurately, using 4 bytes of memory, making it more compact but less precise than double.

Example: float Precision

c
#include <stdio.h>
int main() {
	float f = 1.0f / 3.0f;
	printf("%.7f", f);
	return 0;
}

double Precision

double is a double-precision floating-point type that typically stores about 15 to 16 significant decimal digits, using 8 bytes of memory, and is the default choice for decimal literals and most floating-point math in C.

Example: double Precision

c
#include <stdio.h>
int main() {
	double d = 1.0 / 3.0;
	printf("%.15f", d);
	return 0;
}

Formatting Decimal Output

printf's %f specifier can be customized with a precision, like %.2f for exactly two decimal places, and a field width to control how the formatted decimal number is aligned and padded in the output.

Example: Formatting Decimal Output

c
#include <stdio.h>
int main() {
	double value = 3.14159;
	printf("%.2f", value);
	return 0;
}

Comparing Floating-Point Numbers

Because floating-point numbers are stored in binary and can't represent every decimal value exactly, comparing two floating-point values for exact equality is unreliable, and checking whether their difference is smaller than a small tolerance is the standard approach instead.

Example: Comparing Floating-Point Numbers

c
#include <stdio.h>
#include <math.h>
int main() {
	double a = 0.1 + 0.2;
	double b = 0.3;
	if (fabs(a - b) < 1e-9) {
		printf("Equal enough");
	}
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.